Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element in Object Array by key value

What is the best structure solution for find element(Object) in Object Array by value of one of the keys.

For example we have array:

var someArray = 
[
  {id:17, color:'black', width:50},
  {id:34, color:'red', width:150},
  {id:49, color:'gree', width:10}
]

and we need to find an Object with id-key = 34.

And each time we will have to do the loop to find the object. I thought about restructuring and having object instead of array like so:

 var someObject = 
    {
      17: {id:17, color:'black', width:50},
      34: {id:34, color:'red', width:150},
      49: {id:49, color:'gree', width:10}
    }

Now we can do it in one step someObject[34], BUT what if we want to keep the order?

Thanks in advance.

like image 878
Stepan Suvorov Avatar asked Feb 10 '26 19:02

Stepan Suvorov


1 Answers

I thought about restructuring and having object instead of array

Yes, that's fine.

BUT what if we want to keep the order?

I tend to use an extra array that contains the keys in the correct order, like

var order = [17, 34, 47];

To loop them, you'd use

for (var i=0; i<order.length; i++) {
    … someObject[order[i]] …
}
like image 81
Bergi Avatar answered Feb 13 '26 08:02

Bergi