Javascript javacscript中的筛选器对象
我有一个包含子对象的对象。我想过滤它们。我已经写了一个过滤代码,但仍停留在如何创建具有相同关系的新对象之间 老照片- 预期结果-Javascript javacscript中的筛选器对象,javascript,algorithm,object,Javascript,Algorithm,Object,我有一个包含子对象的对象。我想过滤它们。我已经写了一个过滤代码,但仍停留在如何创建具有相同关系的新对象之间 老照片- 预期结果- 这很有挑战性!有一种方法可以删除未通过过滤器的节点。如果不想,只需克隆树结构即可 首先,让我们创建一个根元素,以便在第一个元素与筛选条件不匹配时不会拆分树: var tree = {"shape":"root","health":"ultraviolet","children":obj}; // obj is your structure in your quest
这很有挑战性!有一种方法可以删除未通过过滤器的节点。如果不想,只需克隆树结构即可 首先,让我们创建一个根元素,以便在第一个元素与筛选条件不匹配时不会拆分树:
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);
}
});
}
过滤功能将是
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");
以获得您想要的结果。当您通过一些示例输入明确问题时,您将得到更多的回答,预期的输出和您面临的实际问题。我会看一看二叉搜索树删除,这是一个非常类似的概念:我还建议寻找一种从树中删除元素的方法,而不是构建一个新的整体树。jan对于您的答案,我已经等待了很长时间了,我会在晚上核对答案,然后再给你回复