0

I wish to iterate over an array of objects, which for purposes of illustration here are Users. I would like to filter those Users using a search term provided and the value of each of the objects properties.

I have come up with the following working solution, however, I am looking to see if anyone has a more elegant method?

let users = [
  {
    first_name: "Super",
    last_name: "User"
  },
  {
    first_name: "Admin",
    last_name: "Istrator"
  }
];

function filterObjects(collection, term) {
  let filtered = [];
  _.each(collection, obj => {
    _.forOwn(obj, (value, key) => {
      if (value.includes(term)) {
        filtered.push(obj);
      }
    });
  });

  return filtered;
}

console.log(filterUsers(users, "Su"));

[Edit]

I make no assumptions about the structure, or the name, or quantity of any fields on the objects, therefore I do not want to use things like object.field_name === 'something' for example.

Peppermintology
  • 9,343
  • 3
  • 27
  • 51
  • `var filtered = collection.filter(item => item.first_name.includes(term) && item.last_name.includes(term));` – Rafael Herscovici Nov 26 '19 at 11:22
  • @Dementic - Thanks for the response, that will work fine if I know the keys of the object being searched and if there are a limited number. – Peppermintology Nov 26 '19 at 11:24
  • As you can see from @Ori Drori's answer, this was the right way. you should always try to consider `how can i use this`. – Rafael Herscovici Nov 26 '19 at 11:33
  • Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Dexygen Nov 26 '19 at 11:35
  • @GeorgeJempty - Yes, I did. My question was how to improve my functioning solution which I had come up with based on my limited knowledge/Googling of the JS ecosystem. How are any of the answers in the link you provided improvements?! – Peppermintology Nov 26 '19 at 11:42

1 Answers1

1

You can filter, and use _.some() to iterate the values, and check with Array.includes() (or lodash equivalent) if the term exists in the value.

const filterUsers = (collection, term) =>
  collection.filter(o => _.some(o, v => v.includes(term)));

const users = [{"first_name":"Super","last_name":"User"},{"first_name":"Admin","last_name":"Istrator"}];

console.log(filterUsers(users, "Su"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

And the same idea using lodash/fp:

const { filter, some, includes } = _;

const filterUsers = term => filter(some(includes(term)));

const users = [{"first_name":"Super","last_name":"User"},{"first_name":"Admin","last_name":"Istrator"}];

console.log(filterUsers("Su")(users));
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209