krishna krishna - 3 months ago 34
Javascript Question

Filter nested object by keys using lodash

I have a nested object like this-

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


I want to filter this by the following array of titles(so if any title starts with any of these then i want that object)-

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


So end result should be-

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


This is what I did -

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


This filters it but just returns me an array of titles like this -

filteredData = ['Hey', 'Sup']


How do I get the array of filtered objects instead of array of filtered titles?
BTW I'm using lodash 3.10

Answer

You can do this with 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)

Update: To filter objects in array whose title starts with element in filterTitles array you can use filter(), some() and 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)