javacscript中的过滤器对象

时间:2015-05-12 08:38:10

标签: javascript algorithm object

我有包含子对象的对象。我想过滤它们。我编写了一个过滤器代码,但是如何创建一个具有相同关系的新对象。 fiddle

var x = 0
var newobj;

function loop(obj, type1, type2) {
    for (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)

修改

编辑fiddle,其中包含小而清晰的数据,预期结果如下所示

{
    "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"
                }
            ]
        }
    ]
}

旧图片 -

enter image description here

预期结果 -

enter image description here

1 个答案:

答案 0 :(得分:1)

这很有挑战性!有一种方法可以删除没有通过过滤器的节点。如果你不想,只需克隆树结构。

首先,让我们创建一个根元素,这样如果第一个元素与过滤条件不匹配,树就不会分裂:

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

现在removeNode函数将是

function removeNode(victim,parent) {
  // remove the victim from parent's children
  var target = parent.children.indexOf(victim);
  if(target>-1) parent.children.splice(target,1);
  // add victim's children to parent's children
  if(victim.children) parent.children = parent.children.concat(victim.children);
  // don't do this if you need a clone
  delete(victim);
}

过滤功能将是

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: you could skip nodes which passed already
      filter(root,shape,health);
    }
  });
}

所以你可以做到

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

获得理想的结果。