[英]Recursively convert nested arrays to nested objects using object's keys for each array
我想更改此數據結構:
[ { 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()進行循環或類似操作以獲得所需的結構。 我確定我錯過了一個傻點,但是我無法解決這個問題。
幫助將不勝感激!
您可以map
數組並很簡單地構造對象:
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
變量的值。 三個點...
將一個數組散布到單獨的元素中,就像這些元素之間用逗號隔開一樣。
這是使用reduce的有效解決方案。 您也許可以進行更多重構:
const sections = [
{ sectionName: 'SectionOne',
ingredients:
[
{ingredient: 'sugar'},
{ingredient: 'flour'}
]
},
{ sectionName: 'SectionTwo',
ingredients:
[
{ingredient: 'eggs'}, {ingredient: 'water'}
]
},
];
const result = sections.reduce((accumulator, currentValue) => {
const ingredientsObj = currentValue.ingredients.reduce((acc, ingredient) => {
acc[ingredient.ingredient] = {
ingredient: ingredient.ingredient
};
return acc;
}, {});
var sectionObject = {
sectionName: currentValue.sectionName,
ingredients: ingredientsObj
}
accumulator[currentValue.sectionName] = sectionObject;
return accumulator;
}, {});
console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.