英文:
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};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论