[英]Convert array into nested object
假設我有以下數組:['product','model','version']
我想要一個對象,例如:
{
product: {
model: {
version: {
}
}
}
}
但是,該數組是動態的,因此它可以包含2、3或更少的項目。 如何以最有效的方式實現這一目標?
謝謝
只需將其內部翻過來,然后將內部對象依次包裝到外部對象中即可:
const keys = ['product', 'model', 'version']; const result = keys.reverse().reduce((res, key) => ({[key]: res}), {}); // innermost value to start with ^^ console.log(result);
如果我正確理解了請求,那么此代碼可能會滿足您的要求:
function convert(namesArray) {
let result = {};
let nestedObj = result;
namesArray.forEach(name => {
nestedObj[name] = {};
nestedObj = nestedObj[name];
});
return result;
}
console.log(convert(['a', 'b', 'c']));
您也可以使用Array.prototype.reduceRight
做到這一點:
const result = ['product','model','version'].reduceRight((all, item) => ({[item]: all}), {}); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.