2

I try to make a loop in that each iterate item will be added to children of previous one. and it will be element of next one

 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[..]
 }]
 }
 ]
}
]
}
asked Sep 15, 2015 at 7:39
1
  • And what is your question about it? Commented Sep 15, 2015 at 7:47

2 Answers 2

2

Just add in a temporary variable and add the new array to that -

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>

answered Sep 15, 2015 at 7:50
Sign up to request clarification or add additional context in comments.

Comments

1

You need to keep track of the previous element:

// 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
});

That way you always append to the last added element.

NOTE: not tested code...

answered Sep 15, 2015 at 7:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.