在Javascript中查找嵌套对象

时间:2017-12-19 22:28:11

标签: javascript

目前,我通过执行以下操作找到嵌套对象

let optionToRemove = newSections.find((section) => section.id == this.state.currentSectionId).questions
    .find((question) => question.id == questionId).options
        .find((option) => option.id == optionId)

这看起来很乏味,有没有更简单的方法呢?

1 个答案:

答案 0 :(得分:0)

有几种方法可以实现这一目标,顺便说一下:

var findNested = function(obj, key, memo) {
      var i,
          proto = Object.prototype,
          ts = proto.toString,
          hasOwn = proto.hasOwnProperty.bind(obj);

      if ('[object Array]' !== ts.call(memo)) memo = [];

      for (i in obj) {
        if (hasOwn(i)) {
          if (i === key) {
            memo.push(obj[i]);
          } else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
            findNested(obj[i], key, memo);
          }
        }
      }

      return memo;
    }

所以你可以像

一样使用它



var findNested = function(obj, key, memo) {
  var i,
    proto = Object.prototype,
    ts = proto.toString,
    hasOwn = proto.hasOwnProperty.bind(obj);

  if ('[object Array]' !== ts.call(memo)) memo = [];

  for (i in obj) {
    if (hasOwn(i)) {
      if (i === key) {
        memo.push(obj[i]);
      } else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
        findNested(obj[i], key, memo);
      }
    }
  }

  return memo;
}
console.log( findNested({ key: 1}, "key") )
console.log( findNested({ key: 1, inner: { key:2}}, "key") )
console.log( findNested({ key: 1, inner: { another_key:2}}, "another_key") )




如果您更喜欢不同的方法,可以根据.NET LINQ查询语言查看linq库here - 请参阅here