Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript modify array

If I have an array that look like this:

[
   {
       key: some_key,
       payload: { ... }
   }, 
   {
       key: some_key,
       payload: { ... }
   }, 
   {
       key: some_key,
       payload: { ... }
   }, 
   ...
]

and I want to find something using a key and then modify the payload.

Is there any way other than iterating through the array?

I have several concerns about iterating

  1. This array is used by many async functions, I am worried that the index might be invalidated by some other functions during the iteration.
  2. Iteration might lead to a lower performance.

I thought about using a immutable object there, but converting to array before every re-rendering doesn't seem very efficient.

Any good idea?

like image 425
Tianhao Zhou Avatar asked Jun 25 '26 23:06

Tianhao Zhou


1 Answers

Another approach would be to pre-build a map by key of all your items. And pass it along the array.

{
  some_key: {
    key: some_key,
    payload: {}
  },
  some_other_key: {
    key: some_other_key,
    payload: {}
  },
  ...
}

You can still have the array as another representation of your data. The actual items, would be exact the same, because the map would just reference the real items in the list, but you could have the fastest possible access performance without searching at all.

This example shows, that the actual payload is still the same data, just another (indexed) representation of it.

const array = [
  { key: 'one' },
  { key: 'two' }
];

const map = array.reduce((acc, item) => {
  acc[item.key] = item;
  return acc;
},{});

array[0] === map.one // true
like image 66
webdeb Avatar answered Jun 27 '26 12:06

webdeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!