如何从对象数组映射所需数据并返回包含这些值的两个新对象

问题描述 投票:0回答:1

我如何从对象数组中提取所需的数据并分配给两个新对象, 下面的例子:

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"
}

试过这个:

const firstNewObject = secondNewObject = sourceObject.sourceArray.map(({cost, description}) => ({cost, description }));

它有效,但返回 2 个新数组,其中包含一个包含成本和描述的对象

我需要像 firstNewObject.cost 一样显示成本值 ES6 的最佳方式是什么?谢谢

javascript arrays javascript-objects
1个回答
0
投票

我想不出任何好的捷径。只需从数组元素创建两个包含所需属性的对象。

const element = ourceObject.sourceArray[0];
const firstNewObject = {cost: element.cost, description: element.description};
const secondNewObject = {cost: element.cost, description: element.description};
© www.soinside.com 2019 - 2024. All rights reserved.