【发布时间】:2017-04-24 09:06:13
【问题描述】:
我有一个对象数组,我想将其转换为以id 为键的键值对映射。但是,我想在根级别和 recipes 属性中都这样做。
数组resp:
[
{
"id": "1",
"recipes": [
{
"id": 4036
},
{
"id": 4041
}
]
},
{
"id": "2",
"recipes": [
{
"id": 4052
},
{
"id": 4053
}
]
}
]
期望的结果
{
"1": {
"id": "1",
"recipes": {
"4036": {
"id": 4036
},
"4041": {
"id": 4041
}
}
},
"2": {
"id": "2",
"recipes": {
"4052": {
"id": 4052
},
"4053": {
"id": 4053
}
}
}
}
我知道如何通过以下函数使用 lodash:
使用 Underscore.js
function deepKeyBy(arr, key) {
return _(arr)
.map(function(o) { // map each object in the array
return _.mapValues(o, function(v) { // map the properties of the object
return _.isArray(v) ? deepKeyBy(v, key) : v; // if the property value is an array, run deepKeyBy() on it
});
})
.keyBy(key); // index the object by the key
}
然而,对于这个项目,我正在寻找一个优雅的解决方案,使用下划线来做同样的事情 - 使嵌套在数组中的所有对象都使用 id 作为键。有人知道怎么做吗?
谢谢!
编辑:添加了所需的输出格式
【问题讨论】:
-
你能展示预期结果的结构吗?
-
@hackerrdave 我已经在上面添加了想要的结果
标签: javascript arrays json object underscore.js