我想基于配置数组生成字符串

时间:2018-09-29 15:41:13

标签: javascript java

我有一个对象数组。

[{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下面生成。 任何身体都能帮忙.. 格式化没关系,它只是一个字符串

enter image description here

1 个答案:

答案 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));