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?
Not without a double loop, but there is still room for optimisation:
You could:
forEach callback by using for..of syntaxvalue instead of array[index]??= 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;
}
}
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