使用 lodash 按键过滤嵌套 object

Filter nested object by keys using lodash

我有一个像这样的嵌套 object-

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

我想通过以下标题数组过滤它(所以如果任何标题以其中任何一个开头,那么我想要 object)-

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)
        )
      )
  );

这会过滤它,但只是 returns 我是这样的标题数组 -

filteredData = ['Hey', 'Sup']

如何获取过滤后的 object 数组而不是过滤后的标题数组? 顺便说一句,我正在使用 lodash 3.10

您可以使用 Array#filter() and 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 数组中的元素开头的数组 objects,您可以使用 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)

即使键的长度不同,您也可以按如下方式操作。这实际上是elasticsearch的代码。

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>