0

I have javascript function who need add position attribute on object.

function conv(data){
var result=[];
function dfs(node, parent) {
    for(var i in node){
        result.push({id:node[i].id,pid:parent});
        if (node[i]['children']) dfs(node[i]['children'],node[i]['id']);
    }
}
dfs(data, 0);
return result;
}

DEMO

So I got result = [{"id":1,"pid":0},{"id":4,"pid":1},{"id":2,"pid":0}]

Need add position something like:

[
{"id":1,"pid":0,"position":100}, // First root
{"id":4,"pid":1,"position":100}, // First sub root
{"id":5,"pid":1,"position":101}, // Second sub root
{"id":2,"pid":0,"position":101}, // Second root
{"id":3,"pid":0,"position":102}, // Third root
]

UPDATE

Position always starts from 100 so its var can be static.

2
  • Where does the value of position comes from, is it computed from the position on the tree ? Commented Oct 12, 2013 at 7:45
  • Oh Sory..See my update! Commented Oct 12, 2013 at 7:54

1 Answer 1

2

Without further information, it seems you just need to add the position to the object you push in the array:

result.push({id:node[i].id,pid:parent,position:position});

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.