gpt4 book ai didi

Javascript如何遍历对象以拾取选定的项目

转载 作者:行者123 更新时间:2023-11-30 11:32:16 25 4
gpt4 key购买 nike

我想遍历 data 对象并从中选择两个项目,即 yearrevenue 并将其放入一个新对象中

var data [{"year": 2014, "revenue": 20000, "costs": 10000, "hours": 50}, {"year": 2015, "revenue": 30000, "costs": 20000, "hours": 54}, {"year": 2016, "revenue": 30000, "costs": 10000, "hours": 40}]

var pickedData = {};

data.forEach(output)

function output(d) {
Object.assign({}, pickedData.Year = d.year),
Object.assign({}, pickedData.Revenue = d.revenue)
}

该代码有效,但仅将 data 中的最后一项分配给新对象 pickedData,这意味着它会循环它但不会每次都为对象分配值通过。我怎样才能得到这样的输出:

console.log(pickedData)
[{Year: 2014, Revenue: 20000}, {Year: 2015, Revenue: 30000}, {Year: 2016, Revenue: 30000}]

最佳答案

您可以改用 map() 方法并返回新数组作为结果。

var data = [{"year": 2014, "revenue": 20000, "costs": 10000, "hours": 50}, {"year": 2015, "revenue": 30000, "costs": 20000, "hours": 54}, {"year": 2016, "revenue": 30000, "costs": 10000, "hours": 40}]

var result = data.map(({year, revenue}) => ({year, revenue}));
console.log(result)

关于Javascript如何遍历对象以拾取选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45787114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com