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[..]
                }]
        }
    ]
}
]
}
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>

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...

Comments

Your Answer

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