使用数组中的循环创建嵌套对象

时间:2015-09-15 07:39:13

标签: jquery

我尝试制作一个循环,每个迭代项将被添加到前一个的子项中。它将成为下一个的元素

 subnodes ={
        id : "value1",
        text:"value1",
        children:[]
    };
    temp ={};
    allnodes = ["value2","value3","value4",...]
    $.each(allnodes,function(index, value){

            newObject = {
                id : value,
                text:value,
                children:[]
            };
            subnodes.children.push(newObject)

    });
after loop result should be like this:
{
    id:"value1",
        text:"value1"
    children:[
        {
            id:"value2",
            text:"value2",
            children:[
                {
                    id:"value3",
                    text:"value3",
                    children[{
                        id:"value4",
                        text:"value4",
                        children[..]
                }]
        }
    ]
}
]
}

2 个答案:

答案 0 :(得分:1)

您需要跟踪上一个元素:

// Starting from subnodes element
var prev = subnodes;
$.each(allnodes,function(index, value){

        var newObject = {
            id : value,
            text:value,
            children:[]
        };
        // Append new element
        prev.children.push(newObject)
        // Set the new element as prev (so next time you append to it)
        prev = newObject

});

这样你总是附加到最后添加的元素。

注意:未经过测试的代码......

答案 1 :(得分:1)

只需添加一个临时变量并将新数组添加到其中 -

subnodes = {
  id: "value1",
  text: "value1",
  children: []
};
temp = {};
allnodes = ["value2", "value3", "value4", "value4"]
var currentnode = subnodes;
$.each(allnodes, function(index, value) {
  newObject = {
    id: value,
    text: value,
    children: []
  }
  currentnode.children.push(newObject);
  currentnode = newObject;
});
$("#result").text(JSON.stringify(subnodes))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>