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
user4005632
-
And what is your question about it?DocRattie– DocRattie2015年09月15日 07:47:50 +00:00Commented Sep 15, 2015 at 7:47
2 Answers 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
John C
3,1123 gold badges36 silver badges50 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
urban
5,7303 gold badges22 silver badges50 bronze badges
Comments
lang-js