gpt4 book ai didi

javascript - Lodash 从嵌套对象中提取值

转载 作者:行者123 更新时间:2023-12-01 00:25:00 26 4
gpt4 key购买 nike

我有以下对象,我当前正在循环该对象以获取项目值。目前我正在使用 lodash _.forEach 来实现这一点。我不确定创建一个以项目名称作为键、以值作为值的新对象的最佳方式是什么。

data =  [
{
"panels" : [
{
"title": "Panel 1",
"items" : [
{
"name": item1,
"value": 1
}
{
"name": item2,
"value": 2
}
]
},
{
"title": "Panel 2",
"items" : [
{
"name": item3,
"value": 3
}
{
"name": item4,
"value": 5
}
]
}
]
}

{
"panels" : [
{
"title": "Panel 3"
"items" : [
{
"name": item5,
"value": 5
}
{
"name": item6,
"value": 6
}
]
}
]
}
]

let values = [];
_.forEach(data, (groups) => {
_.forEach(groups.panels, (panel) => {
_.forEach(panel.items, (item) => {
values[item.name] = item.value;
});
});
});
return values;

还有其他方法可以更有效地实现这一目标吗?

最佳答案

您可以使用嵌套的 for...of循环 destructuring

const data=[{panels:[{title:"Panel 1",items:[{name:"item1",value:1},{name:"item2",value:2}]},{title:"Panel 2",items:[{name:"item3",value:3},{name:"item4",value:5}]}]},{panels:[{title:"Panel 3",items:[{name:"item5",value:5},{name:"item6",value:6}]}]}];

const output = {};

for (const { panels } of data)
for (const { items } of panels)
for (const { name, value } of items)
output[name] = value;

console.log(output)

或者,

您可以使用链接的 flatMap获取一系列项目。然后减少项目数组以获取一个以name为键、以value为值的对象

const data=[{panels:[{title:"Panel 1",items:[{name:"item1",value:1},{name:"item2",value:2}]},{title:"Panel 2",items:[{name:"item3",value:3},{name:"item4",value:5}]}]},{panels:[{title:"Panel 3",items:[{name:"item5",value:5},{name:"item6",value:6}]}]}];

const output = data.flatMap(o => o.panels)
.flatMap(p => p.items)
.reduce((acc, o) => ({ ...acc, [o.name]: o.value }), {})

console.log(output)

关于javascript - Lodash 从嵌套对象中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59086435/

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