Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace undefined with 0s in array of objects without double for-loop in Javascript

let zed = [
    { name: 'tom', stat1: undefined, stat2: 3 },
    { name: 'nic', stat1: undefined, stat2: undefined },
    { name: 'joe', stat1: 5, stat2: undefined },
]

zed.forEach((value, index, array) => {
    Object.keys(value).forEach(key => {
        array[index][key] = array[index][key] === undefined ? 0 : array[index][key];
    });
});

The code above works but we are concerned about performance on much larger arrays of objects in our react application. Also not sure if mutating the array inside of a forEach() is considered a bad practice in React, perhaps it is better to create a new array somehow with .map(). Any recommendations on the best way to replace undefined with 0?

like image 886
Canovice Avatar asked Jun 26 '26 12:06

Canovice


1 Answers

Not without a double loop, but there is still room for optimisation:

You could:

  • Avoid the forEach callback by using for..of syntax
  • Use value instead of array[index]
  • Use the ??= assignment operator (which will also replace null)
for (const value of zed) {
    for (const key of Object.keys(value)) {
        value[key] ??= 0;
    }
}

If you are sure that the objects in zed have no other enumerable keys other than own keys, you can use in:

for (const value of zed) {
    for (const key in value) {
        value[key] ??= 0;
    }
}
like image 167
trincot Avatar answered Jun 29 '26 01:06

trincot



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!