javascript根据键值过滤嵌套对象 [英] javascript filter nested object based on key value

查看:21
本文介绍了javascript根据键值过滤嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过step"键的值过滤嵌套的 javascript 对象:

I wish to filter a nested javascript object by the value of the "step" key:

var data = {
"name": "Root",
"step": 1,
"id": "0.0",   
"children": [
    {
    "name": "first level child 1",
    "id": "0.1",
    "step":2,
    "children": [
        {
        "name": "second level child 1",
        "id": "0.1.1",
        "step": 3,
        "children": [
            {
            "name": "third level child 1",
            "id": "0.1.1.1",
            "step": 4,
            "children": []},
        {
            "name": "third level child 2",
            "id": "0.1.1.2",
            "step": 5,
            "children": []}

        ]},
                ]}
]

};

var subdata = data.children.filter(function (d) {
        return (d.step <= 2)});

这只会返回未修改的嵌套对象,即使我将过滤器的值设置为 1..filter 是否适用于嵌套对象,或者我是否需要在这里滚动我自己的函数,建议和正确的代码表示赞赏.cjm

This just returns the unmodified nested object, even if I put value of filter to 1. does .filter work on nested objects or do I need to roll my own function here, advise and correct code appreciated. cjm

推荐答案

递归过滤器函数相当容易创建.这是一个例子,它剥离了一个 JS 对象中定义的所有项目 ["depth","x","x0","y","y0","parent","size"]:

Recursive filter functions are fairly easy to create. This is an example, which strips a JS object of all items defined ["depth","x","x0","y","y0","parent","size"]:

function filter(data) {
  for(var i in data){
    if(["depth","x","x0","y","y0","parent","size"].indexOf(i) != -1){
       delete data[i]; 
    } else if (i === "children") {
      for (var j in data.children) {
        data.children[j] = filter(data.children[j])
      }
    }  
  }
  return data;
}

如果您想按其他方式过滤,只需使用您选择的过滤功能更新第二行.

If you would like to filter by something else, just updated the 2nd line with your filter function of choice.

这篇关于javascript根据键值过滤嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆