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

huangapple go评论66阅读模式
英文:

How to map desired data from an array of objects and return two new objects containing those values

问题

以下是您要翻译的内容:

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

const sourceObject = {
 key1: "value1",
 key2: "value2",
 sourceArray: [{
   cost: 10,
   time: 30,
   shift: 1,
   description: "text",
   name: "John"
 }]
}

我想从源对象中提取cost和description,并分配给两个新对象,以获得以下最终结果:

firstNewObject = {
  cost: 10,
  description: "text"
}

secondNewObject = {
  cost: 10,
  description: "text"
}

尝试了以下方法:

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

它能够工作,但返回包含cost和description的对象的两个新数组。

我需要以firstNewObject.cost的方式显示cost的值。使用ES6,有什么最佳方法吗?谢谢!

英文:

How i can extract just the desired data from an array of objects and assign to two new objects,
example below:

const sourceObject = {
 key1: "value1",
 key2: "value2",
 sourceArray: [{
   cost: 10,
   time: 30,
   shift: 1,
   description: "text",
   name: "John"
 }]
}

i want to extract cost & description from the source and assign to the two new objects, to get this as the final result:

firstNewObject = {
  cost: 10,
  description: "text"
}

secondNewObject = {
  cost: 10,
  description: "text"
}

tried this:

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

it works but returns 2 new arrays with an object containing cost & description

i need to display the value for cost like firstNewObject.cost
what is the best way with ES6? thank you

答案1

得分: 0

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

const element = sourceObject.sourceArray[0];
const firstNewObject = {cost: element.cost, description: element.description};
const secondNewObject = {cost: element.cost, description: element.description};
英文:

I can't think of any nice shortcut. Just create two objects containing the desired properties from the array element.

const element = ourceObject.sourceArray[0];
const firstNewObject = {cost: element.cost, description: element.description};
const secondNewObject = {cost: element.cost, description: element.description};

huangapple
  • 本文由 发表于 2023年5月18日 06:10:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定