我有一个对象数组,我想将其转换为以 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
作为键。有人知道该怎么做吗?
谢谢!
编辑:添加所需的输出格式
最佳答案
我会在响应上使用 Array.reduce 并在配方上使用嵌套的 Array.reduce 来产生所需的结果。这是一个 es6 示例:
resp.reduce((p, c) => {
p[c.id] = {
id: c.id,
recipes: c.recipes.reduce((r, cr) => {
r[cr.id] = { id: cr.id }
return r;
}, {})
}
return p;
}, {});
更详细的非 es6 版本:
var resp = [
{
"id": "1",
"recipes": [
{
"id": 4036
},
{
"id": 4041
}
]
},
{
"id": "2",
"recipes": [
{
"id": 4052
},
{
"id": 4053
}
]
}
]
var formatted = resp.reduce(function(data, cur) {
data[cur.id] = {
id: cur.id,
recipes: cur.recipes.reduce(function(recips, curRecip) {
recips[curRecip.id] = { id: curRecip.id }
return recips;
}, {})
}
return data;
}, {});
console.log(formatted);
如果您必须使用下划线,则可以将resp
和c.recipes
括起来:
_(resp).reduce((p, c) => {
p[c.id] = {
id: c.id,
recipes: _(c.recipes).reduce((r, cr) => {
r[cr.id] = { id: cr.id }
return r;
}, {})
}
return p;
}, {});
关于javascript - 下划线表示多个嵌套级别数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051052/