javascript - filter object in javacscript -


i have object contains child object well. want filter them. have written filter code stuck between how create new object same relation. fiddle

var x = 0 var newobj;  function loop(obj, type1, type2) {     (i in obj) {         if (obj[i].shape == type1 && obj[i].health == type2) {             $('div').append(obj[i].shape + '-' + obj[i].health + '<br>')             if (!x) {                 newobj = obj[i];             } else {                 newobj.children = obj[i]             }             x++         }         loop(obj[i].children, type1, type2)     } }  function filter() {     loop(obj, 'circle', 'red') }  filter()  console.log(newobj) 

edit

edited fiddle small , clear data , expected result given below

{     "shape": "circle",     "health": "red",     "children": [         {             "shape": "circle",             "health": "red"         },         {             "shape": "circle",             "health": "red"         },         {             "shape": "circle",             "health": "red",             "children": [                 {                     "shape": "circle",                     "health": "red"                 },                 {                     "shape": "circle",                     "health": "red"                 }             ]         }     ] } 

old picture -

enter image description here

expected result-

enter image description here

that's challenging! there way in removing nodes doesn't pass filter. if don't want to, clone tree structure.

first, let's create root element tree don't split if first element doesn't match filter condition:

var tree = {"shape":"root","health":"ultraviolet","children":obj}; // obj structure in question 

now removenode function be

function removenode(victim,parent) {   // remove victim parent's children   var target = parent.children.indexof(victim);   if(target>-1) parent.children.splice(target,1);   // add victim's children parent's children   if(victim.children) parent.children = parent.children.concat(victim.children);   // don't if need clone   delete(victim); } 

and filter function be

function filter(root,shape,health) {   if(root.children) root.children.foreach(function(o) {     filter(o,shape,health);     if(!(o.shape==shape && o.health==health) && o.shape!="root") {       removenode(o,root);       // possible optimization: skip nodes passed       filter(root,shape,health);     }   }); } 

so can do

filter(tree,"circle","red"); 

to desired result.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -