如何在深层Javascript对象中查找具有特定值的键数?

时间:2016-12-02 13:35:28

标签: javascript

我有以下深层Javascript对象,如何找到值为“type”的“foo”键的数量?

{
    ...
    blocks: [{
        items: [{
            type: "foo"
        },
        {
            type: "subBlock",
            items: [{
                type: "foo"
            }]
        }]
    },
    {
        items: [{
            type: "foo"
        },
        {
            type: "foo"
        }]
    }]
    ...
}

1 个答案:

答案 0 :(得分:0)

您可以创建递归函数,循环数据结构并返回总计数。

var obj = {
  blocks: [{
    items: [{
      type: "foo"
    }, {
      type: "subBlock",
      items: [{
        type: "foo"
      }]
    }]
  }, {
    items: [{
      type: "foo"
    }, {
      type: "foo"
    }]
  }]
}

function countFoo(data) {
  var result = 0;
  if (typeof data == 'object' && !Array.isArray(data)) {
    Object.keys(data).forEach(function(e) {
      if (e == 'type' && data[e] == 'foo') {
        result++;
      } else if (typeof data[e] == 'object') {
        result += countFoo(data[e]);
      }
    })
  } else if (Array.isArray(data)) {
    data.forEach(function(e) {
      if (typeof e == 'object') {
        result += countFoo(e);
      }
    })
  }
  return result;
}

console.log(countFoo(obj))