繁体   English   中英

使用lodash按键过滤嵌套对象

[英]Filter nested object by keys using lodash

我有一个像这样的嵌套对象 -

data = [{ 'title': 'Hey',
   'foo': 2,
   'bar': 3
 }, {
  'title': 'Sup',
  'foo': 3,
  'bar': 4
 }, {
  'title': 'Remove',
  'foo': 3,
  'bar': 4
}]

我想通过以下标题数组过滤这个(所以如果任何标题以任何这些标题开头那么我想要那个对象) -

const filterTitles = ['He', 'Su']

所以最终结果应该是 -

filteredData = [{ 'title': 'Hey',
   'foo': 2,
   'bar': 3
 }, {
  'title': 'Sup',
  'foo': 3,
  'bar': 4
 }]

这就是我做的 -

filteredData = _.map(data, section => 
    _.pick(section,val => 
      _.some(filterTitles, title => 
        _.startsWith(val, title)
        )
      )
  );

这会过滤它但只返回一个像这样的标题数组 -

filteredData = ['Hey', 'Sup']

如何获取过滤对象数组而不是过滤标题数组? 顺便说一下,我正在使用lodash 3.10

您可以使用Array#filter()Array#includes()

 var data = [{ 'title': 'Hey', 'foo': 2, 'bar': 3 }, { 'title': 'Sup', 'foo': 3, 'bar': 4 }, { 'title': 'Remove', 'foo': 3, 'bar': 4 }] const filterTitles = ['Hey', 'Sup']; var result = data.filter(function(o) { return filterTitles.includes(o.title); }); console.log(result) 

更新:要过滤其标题以filterTitles数组中的元素开头的数组中的对象,您可以使用filter()some()startsWith()

 var data = [{ 'title': 'Hey', 'foo': 2, 'bar': 3 }, { 'title': 'Sup', 'foo': 3, 'bar': 4 }, { 'title': 'Remove', 'foo': 3, 'bar': 4 }] const filterTitles = ['He', 'Su'] var result = data.filter(function(o) { return filterTitles.some(function(e) { return o.title.startsWith(e); }) }); console.log(result) 

即使键长度不同,您也可以执行以下操作。 这实际上是弹性搜索的代码。

 var data = [{ 'title': 'Hello', 'foo': 2, 'bar': 3 }, { 'title': 'Support', 'foo': 3, 'bar': 4 }, { 'title': 'Remove', 'foo': 3, 'bar': 4 }], keys = ["he","sup"], filtered = keys.reduce((res,k) => res.concat(data.filter(o => o.title.slice(0,k.length).toLowerCase() === k.toLowerCase())),[]); console.log(filtered); 

在lodash中的解决方案。

 var data = [{ 'title': 'Hey', 'foo': 2, 'bar': 3 }, { 'title': 'Sup', 'foo': 3, 'bar': 4 }, { 'title': 'Remove', 'foo': 3, 'bar': 4}], filterTitles = ['He', 'Su'], result = _.filter(data, o => _.some(filterTitles, title => _.startsWith(o.title, title))); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM