-3

I have a question whats the best way to filter the object that has an array of objects and i would like to return an object that has the matching property

const test = Object.keys(repo).map((keyName, i) => {
   if(repo[keyName].name === post_name) {
     console.log(repo[keyName])
   } 
})

the code above works but i feel like its not a best way to achieve it maybe someone has a better way of solving this.

user9013856
  • 328
  • 2
  • 10
  • how does the code works for you? – Nina Scholz Jun 02 '19 at 21:15
  • Possible duplicate of [Find a value in an array of objects in Javascript](https://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript) – L777 Jun 02 '19 at 21:18

1 Answers1

2

If you want to filter an existing array and create a new array, you should use .filter. Only use .map when you're creating another array from every element in an existing array - don't use it for side effects.

You can use Object.values instead of Object.keys, since it looks like you only care about the values:

const test = Object.values(repo).filter(({ name }) => name === post_name);

Then you'll have an array of the objects with a matching name.

If you know that there's only going to be one matching object, use .find instead:

const match = Object.values(repo).find(({ name }) => name === post_name);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320