在Javascript中查找嵌套对象

问题描述 投票:1回答:1

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

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

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

javascript
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.