Find object by match property in nested array

穿精又带淫゛_ 提交于 2019-12-17 18:12:11

问题


I'm not seeing a way to find objects when my condition would involve a nested array.

var modules = [{
    name: 'Module1',
    submodules: [{
        name: 'Submodule1',
        id: 1
      }, {
        name: 'Submodule2',
        id: 2
      }
    ]
  }, {
    name: 'Module2',
    submodules: [{
        name: 'Submodule1',
        id: 3
      }, {
        name: 'Submodule2',
        id: 4
      }
    ]
  }
];

This won't work because submodules is an array, not an object. Is there any shorthand that would make this work? I'm trying to avoid iterating the array manually.

_.where(modules, {submodules:{id:3}});

回答1:


Here's what I came up with:

_.find(modules, _.flow(
    _.property('submodules'),
    _.partialRight(_.some, { id: 2 })
));
// → { name: 'Module1', ... }

Using flow(), you can construct a callback function that does what you need. When call, the data flows through each function. The first thing you want is the submodules property, and you can get that using the property() function.

The the submodules array is then fed into some(), which returns true if it contains the submodule you're after, in this case, ID 2.

Replace find() with filter() if you're looking for multiple modules, and not just the first one found.




回答2:


Lodash allows you to filter in nested data (including arrays) like this:

_.filter(modules, { submodules: [ { id: 2 } ]});




回答3:


I think your best chance is using a function, for obtaining the module.

_.select(modules, function (module) {
  return _.any(module.submodules, function (submodule) {
    return _.where(submodule, {id:3});
  });
});

try this for getting the submodule

.where(.pluck(modules, "submodules"), {submodules:{id:3}});



来源:https://stackoverflow.com/questions/30107463/find-object-by-match-property-in-nested-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!