StackOverflow - StackOverflow
How to update all items in an Array with Airbnb JavaScript Style?
Let's say that we have an array like this:
let list = [
{
name: '1',
count: 0,
},
{
name: '2',
count: 10,
},
{
name: '3',
count: 18,
},
];
Then how to update all items to increase count
by 1?
Here comes several solutions, while none of them is quite satisfactory:
/* no-restricted-syntax error, pass */
for (const item of list) {
item.count += 1;
}
/* no-param-reassign error, pass */
list.forEach((item) => {
item.count += 1;
});
/*
Object.assign is free to use without error
but it against the intention of no-param-reassign
*/
list.forEach((item) => {
Object.assign(item, { count: item.count + 1 });
});
/*
use Array.map() to replace the original array
but it costs a lot when the item is large or the array has a large length
also ugly code for such a tiny update
*/
list = list.map((item) => ({
...item,
count: item.count + 1,
}));
If you have a better solution or consider Array.map()
is good enough, please leave your opinion.
Thank you :)
Was this helpful?
Related Articles
Have a different question?
Can't find the answer you're looking for? Submit your own question to our community.
🛎️ Get Weekly OTA Fixes
New answers, vendor issues, and updates — straight to your inbox.