我想更改此数据结构:
[ { sectionName: 'SectionOne',
ingredients: [ {ingredient: 'sugar'}, {ingredient: 'flour'} ]},
{ sectionName: 'SectionTwo',
ingredients: [ {ingredient: 'eggs'}, {ingredient: 'water'} ] },
]
对此:
{ SectionOne:
{ sectionName: 'SectionOne',
ingredients: {
sugar: { ingredient: 'sugar' },
flour: { ingredient: 'flour' }
}
},
{ SectionTwo:
{ sectionName: 'SectionTwo',
ingredients: {
eggs: { ingredient: 'eggs' },
water: { ingredient: 'water' }
}
},
}
换句话说,我想对每个要转换为对象的数组使用对象的键。
您可以在此找到数据结构的示例 jsfddle 连同我的尝试。
到目前为止,使用 lodash 或 vanillaJS 我只能转换外部数组。 我无法设法递归地使用 _.mapKeys()、for 循环或类似的方法来获得所需的结构。我确信我错过了一个愚蠢的观点,但我无法解决这个问题。
非常感谢您的帮助!
最佳答案
您可以映射
一个数组并非常简单地构造您的对象:
const data = [
{ sectionName: 'SectionOne',
ingredients: [ {ingredient: 'sugar'}, {ingredient: 'flour'} ]},
{ sectionName: 'SectionTwo',
ingredients: [ {ingredient: 'eggs'}, {ingredient: 'water'} ] },
];
const res = Object.assign(...data.map(el => ({ // for every element
[el.sectionName]: {
sectionName: el.sectionName,
ingredients: Object.assign(...el.ingredients.map(e => ({[e.ingredient]: e}))) // assign each object inside array
}
})))
console.log(res)
console.log(res.SectionOne.ingredients.sugar)
这里[something]
表示法创建一个键,其名称是something
变量的值。三个点 ...
将数组分散为单独的元素,就像这些元素只是用逗号分隔一样。
关于javascript - 使用每个数组的对象键将嵌套数组递归转换为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44593583/