我不知道这样,所以我需要帮助。所以我有这个对象
{
"label": "root",
"children": [
{
"label": "a",
"value": "abc"
},
{
"label": "b",
"value": 123
},
{
"label": "c",
"children": [
{
"label": 0,
"children": [
{
"label": "d",
"value": "def"
},
{
"label": "e",
"value": 1
},
{
"label": "f",
"children": [
{
"label": 0,
"children": [
{
"label": "g",
"value": "ghi"
},
{
"label": "h",
"value": 456
}
]
}
]
}
]
},
{
"label": 1,
"children": [
{
"label": "i",
"value": 1
},
{
"label": "j",
"value": "abc"
},
{
"label": "asd",
"children": [
{
"label": 0,
"children": [
{
"label": "qwe",
"value": "kuracpalac"
},
{
"label": "rtz",
"value": "asdasdasdasd"
}
]
}
]
}
]
}
]
}
]
}
,我需要它将其转换为看起来像这样的新对象:
const obj = {
a: "abc",
b: 123,
c: [
{
d: "def",
e: 1,
f: [
{
g: "ghi",
h: 456
}
]
},
{
i: 1,
j: "abc",
asd: {
qwe: "kuracpalac",
rtz: "asdasdasdasd"
}
}
]
};
谢谢您的帮助:)!
答案 0 :(得分:2)
您可以使用两个函数,一个用于获取数组,具体取决于键(是整数值还是指定的对象)。另一个函数返回一个具有新键/值对的对象,该对象是值或子元素数组的嵌套对象结构。
function assign(array) {
return Object.assign(0 in array[0] ? [] : {}, ...array);
}
function getObject({ label, value, children }) {
return { [label]: value || assign(children.map(getObject)) };
}
var data = { label: "root", children: [{ label: "a", value: "abc" }, { label: "b", value: 123 }, { label: "c", children: [{ label: 0, children: [{ label: "d", value: "def" }, { label: "e", value: 1 }, { label: "f", children: [{ label: 0, children: [{ label: "g", value: "ghi" }, { label: "h", value: 456 }] }] }] }, { label: 1, children: [{ label: "i", value: 1 }, { label: "j", value: "abc" }, { label: "asd", children: [{ label: 0, children: [{ label: "qwe", value: "kuracpalac" }, { label: "rtz", value: "asdasdasdasd" }] }] }] }] }] },
result = getObject(data).root;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }