我尝试创建一个循环,每个迭代项都将添加到前一个迭代项的子项中。它将成为下一个的元素
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[..]
}]
}
]
}
]
}
最佳答案
只需添加一个临时变量并将新数组添加到其中 -
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>
关于jquery - 在数组中创建带有循环的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32580349/