-1

I have an array of Objects with IDs. The Array looks something like this:

   var array = [
       {
           "id": 0,
           "name": "Test"
       },

       {
           "id": 1,
           "name": "Test2"
       },
   ]

I'd like to know how I could now access an object that has a specific value in their attribute. I.e. I'd like to access the object with id = 0 or the object with `name = "Test2" and so on.

What's the most efficient way to do so?

alex
  • 576
  • 4
  • 25
  • 1
    Your objects are invalid. They property key/values should be separated by a colon, not an equals sign. See also [working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects), and [arrays](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays). The [`find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) method maybe useful. – Andy Feb 25 '23 at 16:12
  • @Andy You're right, sorry about that. In my code the objects were correct, I simply wrote the example wrong. – alex Feb 25 '23 at 19:06

1 Answers1

1

My Answer:

var array = [
   {
       "id": 0,
       "name": "Test"
   },
   {
       "id": 1,
       "name": "Test2"
   },
];


console.log(array.filter(ele=>ele.id === 0));
console.log(array.filter(ele=>ele.name === 'Test2'));

array.filter() works well than find(). This is because find() finds only 1 item according to the order of array.

tzztson
  • 328
  • 3
  • 22
  • Thank you, this answer is great! `find()` would've worked for what the question was intended for in this case, but I actually have a case later where I would rather need `filter()`, so knowing about both is super helpful. – alex Feb 25 '23 at 19:08