我有一个对象数组。
[{id:"a5", parent: a3, value:"great grand child conmpnent"},
{id:"a1", parent: null, value:"parent conmpnent"},
{id:"a2", parent: a1, value:"child conmpnent"},
{id:"a3", parent: a2, value:"grand child conmpnent"},
{id:"a4", parent: a2, value:"grand child conmpnent"}]
我想基于此数组在String下面生成。 任何身体都能帮忙.. 格式化没关系,它只是一个字符串
答案 0 :(得分:0)
我解决了这个问题...
var arr = [{ id: "a5", parent: "a3", value: "great grand child conmpnent" },
{ id: "a1", parent: null, value: "parent conmpnent" },
{ id: "a2", parent: "a1", value: "child conmpnent" },
{ id: "a3", parent: "a2", value: "grand child conmpnent" },
{ id: "a4", parent: "a2", value: "grand child conmpnent" }];
const transform = (arr, parent) => {
var str = '';
for (let key in arr) {
if (arr[key].parent == parent) {
str+= '<ul><li id="'+arr[key].id+'"><a>'+arr[key].value+'</a>'+ transform(arr, arr[key].id)+'</li></ul>';
}
}
return str;
}
var generate = (arr) => {
let parent = '';
let str = '';
for(let key in arr){
if(arr[key].parent == null){
parent = arr[key];
}
}
str = transform(arr, parent.id);
return '<ul><li id="'+parent.id+'"><a>'+parent.value +'</a>'+ str +'</li></ul>';
}
console.log(generate(arr));