如何从对象数组提取指定数据并赋值给两个新对象(ES6实现)
ES6 实现从对象数组提取字段生成独立对象
问题场景
给定包含对象数组的源数据,需要从数组的第一个元素中提取cost和description字段,赋值给两个独立的新对象,要求能直接通过对象属性(如firstNewObject.cost)访问对应值。
源数据示例
const sourceObject = { key1: "value1", key2: "value2", sourceArray: [{ cost: 10, time: 30, shift: 1, description: "text", name: "John" }] }
期望结果
firstNewObject = { cost: 10, description: "text" } secondNewObject = { cost: 10, description: "text" }
尝试过的方法(存在问题)
使用map方法会返回包含对象的数组,无法直接通过属性访问:
const firstNewObject = secondNewObject = sourceObject.sourceArray.map(({cost, description}) => ({cost, description })); // 结果是数组,无法直接调用 firstNewObject.cost
最优实现方案
因为目标是从数组的第一个元素提取字段,不需要遍历整个数组,直接解构数组第一个元素,再提取所需字段即可:
方案1:分步解构
// 先取出数组第一个元素 const [item] = sourceObject.sourceArray; // 提取字段并创建新对象,赋值给两个变量 const firstNewObject = { cost: item.cost, description: item.description }; const secondNewObject = { cost: item.cost, description: item.description };
方案2:一次性解构+对象字面量
更简洁的写法,直接在解构数组的同时提取目标字段:
const [{ cost, description }] = sourceObject.sourceArray; const firstNewObject = { cost, description }; const secondNewObject = { cost, description };
以上两种方案创建的两个新对象是独立的,彼此不会共享引用,修改其中一个对象的属性不会影响另一个。
内容的提问来源于stack exchange,提问作者js_novice
相关产品推荐
相关产品推荐

