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
I thought about using a immutable object there, but converting to array before every re-rendering doesn't seem very efficient.
Any good idea?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With