[英]How to create nested JSON based on array of keys?
給定輸入:
let input = [
{
schema: ["user", "email"],
value: "test@test.com"
},
{
schema: ["user", "name", "firstName"],
value: "John"
},
];
let output = {};
for (let i = 0; i < input.length; i++) {
let data = input[i];
for (let j = 0; j < data.schema.length; j++) {
let s = data.schema[j];
// How to set nested levels here ? eg: output["user"]["email"] = {};
}
}
預期產量:
{
"user": {
"email": "test@test.com",
"name": {
"firstName": "John"
}
}
}
此處,“模式”表示JSON中數據的嵌套結構。
使用Javascript動態設置嵌套屬性的方法是什么?
您可以使用reduce
來“加深”輸出對象,直到需要設置屬性/值的級別為止:
const input = [{schema: ["user", "email"],value: "test@test.com"},{schema: ["user", "name", "firstName"],value: "John"},]; const output = {}; for (const obj of input) { obj.schema.slice(0, -1).reduce( (acc, lvl) => acc[lvl] || (acc[lvl] = {}), output )[obj.schema.slice(-1)[0]] = obj.value; } console.log(output);
這樣,如果架構數組具有兩個以上的值,它也可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.