gpt4 book ai didi

javascript - 下划线 将数组转换为对象键

转载 作者:行者123 更新时间:2023-11-28 07:17:02 25 4
gpt4 key购买 nike

我正在尝试将此数组转换为对象。使用下划线,我想转换这个数组:

[
{
"id": "parentA",
"children": [
{
"name": "name1"
},
{
"name": "name2"
},
{
"name": "name3"
}
]
},
{
"id": "parentB",
"children": [
{
"name": "name4"
},
{
"name": "name5"
},
{
"name": "name6"
}
]
}]

进入一个看起来像这样的对象:

{
"name1": "parentA",
"name2": "parentA",
"name3": "parentA",
"name4": "parentB",
"name5": "parentB",
"name6": "parentB"
}

我真的只是在寻找尽可能最干净/最简单的方法。

最佳答案

这里有一个相当简短的方法来使用两个reduce:

var data = [
{
"id": "parentA",
"children": [
{
"name": "name1"
},
{
"name": "name2"
},
{
"name": "name3"
}
]
},
{
"id": "parentB",
"children": [
{
"name": "name4"
},
{
"name": "name5"
},
{
"name": "name6"
}
]
}];

var out = _.reduce(data, function(result, parent) {
_.reduce(parent.children, function(r, child) {
r[child.name] = parent.id;
return r;
}, result);
return result;
}, {});

document.write(JSON.stringify(out));
<script src="http://underscorejs.org/underscore-min.js"></script>

关于javascript - 下划线 将数组转换为对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30745009/

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