2 回答
TA贡献2037条经验 获得超6个赞
您可以使用reduce和forEach方法来创建嵌套结构以及一个数组,您可以在其中指定要迭代的键的顺序。
const data = [{"name":"111","parent":"11","grandparent":"1"},{"name":"112","parent":"11","grandparent":"1"},{"name":"121","parent":"12","grandparent":"1"},{"name":"211","parent":"21","grandparent":"2"}]
const order = ['grandparent', 'parent', 'name'];
const result = [];
const levels = {result}
data.forEach(o => {
order.reduce((r, e) => {
const name = o[e];
if (!r[name]) {
const value = {name, children: []}
r[name] = {result: value.children}
r.result.push(value)
}
return r[name]
}, levels)
})
console.log(result)
TA贡献1829条经验 获得超6个赞
如果你想用作动态数组值,请使用Object.keys()和reverse
const data = [{"name":"111","parent":"11","grandparent":"1"},{"name":"112","parent":"11","grandparent":"1"},{"name":"121","parent":"12","grandparent":"1"},{"name":"211","parent":"21","grandparent":"2", "grandgrandparente": "3"}]
const result = [];
const levels = {result}
data.forEach(o => {
const order = Object.keys(o).reverse();
order.reduce((r, e) => {
const name = o[e];
if (!r[name]) {
const value = {name, children: []}
r[name] = {result: value.children}
r.result.push(value)
}
return r[name]
}, levels)
})
console.log(result)
添加回答
举报