i have following structure -
{ "fruits":[ { "name":"apples", "id":"1" }, { "name":"pears", "id":"4" }, { "name":"grapes", "id":"5" } ], "links":[ { "source":"1", "target":"5" }, { "source":"4", "target":"5" }, { "source":"9", "target":"10" }, { "source":"1", "target":"10" } ] } i trying remove section of links source , target equal (9 , 10) , (1 , 10).
this has removed aforementioned does not match combination of of id's in fruits section.
so have tried iterate on each link element stuck on how check against each id in fruits object -
for (var = 0; < data.links.length; i++) { // logic } i think along lines of -
if(data.links[i].source || data.links[i].target) // so if data.links[i].source || data.links[i].target not match combination of of id's in fruits object -
delete data.links[i]; so remove -
{ "source":"9", "target":"10" }, { "source":"1", "target":"10" } because neither 9 or 10 present @ in fruits object (therefore remove) , although 1 exist, 10 doesn't, therefore doesn't match combination of of ids in fruit object again remove.
how can achieve resulting structure -
{ "fruits":[ { "name":"apples", "id":"1" }, { "name":"pears", "id":"4" }, { "name":"grapes", "id":"5" } ], "links":[ { "source":"1", "target":"5" }, { "source":"4", "target":"5" } ] }
one way approach iterate through fruits array each element of links, , check source , target against id of each fruit. if @ least 1 doesn't match, remove element links. implemented so:
for (var = data.links.length - 1; >= 0; i--) { var sourceexists = false; var targetexists = false; // check source , target against each fruit id (var j = 0; j < data.fruits.length; j++){ if (data.links[i].source == data.fruits[j].id){ sourceexists = true; } if (data.links[i].target == data.fruits[j].id){ targetexists = true; } } // remove element if either source or target didn't match if (!sourceexists || !targetexists){ data.links.splice(i, 1); } } note how iterate backwards through links array, since removal of element otherwise have unwanted side effects while iterating forwards. here's jsfiddle demonstrate solution.
hope helps! let me know if have questions.
Comments
Post a Comment