给定输入:
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"
}
}
}
这里的"schema“表示数据在JSON中的嵌套结构。
使用Javascript动态设置嵌套属性的方法是什么?
发布于 2018-02-18 20:15:22
您可以使用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);
如果模式数组有2个以上的值,也可以使用这种方法。
https://stackoverflow.com/questions/48851226
复制相似问题