Negin Basiri
Negin Basiri

Reputation: 1375

Filtering list of objects

I rendered a list using Redux and there is a search field to find movies that include the search keyword. My list is an object not an array and if user types: "The" it should filter the list that has 'The' in the title.

{'1':  { 'title': 'A Name' },'2':  { 'title': 'The Name'  },'3':  { 'title': 'The Second Name'  }} 

So the result after filter should be

{'2':  { 'title': 'The Name'  },'3':  { 'title': 'The Second Name'  }}  

How would you do that? Using lodash is a bonus. Thanks

Upvotes: 0

Views: 49

Answers (3)

Ori Drori
Ori Drori

Reputation: 191986

You cay use _.pickBy() as a filter for objects, check if each sub object title _.includes() the search word:

const data = {'1':  { 'title': 'A Name' }, '2':  { 'title': 'The Name'  }, '3':  { 'title': 'The Second Name'  }};

const result = _.pickBy(data, (v) => _.includes(v.title, 'The'));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to iterate over your object keys, filter, and reduce result back to object.

const obj = {'1':  { 'title': 'A Name' },'2':  { 'title': 'The Name'  },'3':  { 'title': 'The Second Name'  }}

console.log(
  Object.keys(obj)
    .filter(key => obj[key].title.includes('The'))
    .reduce((acc, key) => (acc[key] = obj[key], acc), {})
)

Or using lodash#transform

const obj = {'1':  { 'title': 'A Name' },'2':  { 'title': 'The Name'  },'3':  { 'title': 'The Second Name'  }}

console.log(
  _.transform(obj, (result, value, key) => {
    if(value.title.includes('The')) result[key] = value
  }, {})
)
<script src="https://unpkg.com/[email protected]"></script>

Upvotes: 0

Dinesh K
Dinesh K

Reputation: 651

let filteredList = [];
    _.forEach(responseList, function(value) {
      var titleToSearch = value.title.split(" ");
      if(titleToSearch [0]=="The")
             filteredList.push(value);
    });

Kindly try this logic, have not tested though

Upvotes: 0

Related Questions