gpt4 book ai didi

javascript - underscore.js 使用子元素的键值对数组展平对象结构

转载 作者:行者123 更新时间:2023-12-03 06:37:13 24 4
gpt4 key购买 nike

给定以下数据结构:

var data = [{
name: "Some Name",
id: 1,
children: [
{ name: "prop1", value: 1 },
{ name: "prop2", value: 2 },
{ name: "prop3", value: 3 }
]
},
{
name: "Some Other Name",
id: 2,
children: [
{ name: "prop1", value: 4 },
{ name: "prop2", value: 5 },
{ name: "prop3", value: 6 }
]
}];

...其中children是一个动态列表,我使用几个_.each循环“展平”这个结构,如下所示:

_.each(data, d => {
_.each(d.children, c => {
d[c.name] = c.value;
})
});

...仅实现二维数据结构,例如:

[{
name: "Some Name",
id: 1,
prop1: 1,
prop2: 2,
prop3: 3
},
{
name: "Some Other Name",
id: 2,
prop1: 4,
prop2: 5,
prop3: 6
}];

所以我希望有一种巧妙的方法可以通过 undercore.js 来实现这一目标。 ?

JSFiddle 玩:http://jsfiddle.net/3m3dsv47/

最佳答案

我想出的另一个解决方案:

_.each(data, d => {
_.extend(d, _.object(_.map(d.children, c => {
return [c.name, c.value];
})));
});

http://jsfiddle.net/qk2Lu0hu/

关于javascript - underscore.js 使用子元素的键值对数组展平对象结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38142070/

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