Home > Software engineering >  Replace undefined with 0s in array of objects without double for-loop in Javascript
Replace undefined with 0s in array of objects without double for-loop in Javascript

Time:10-23

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?

CodePudding user response:

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;
    }
}

CodePudding user response:

If we trust the JSON.stringfy() built-in function to work efficiently, then the following solution is sure to be very efficient

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

    let result = JSON.stringify(zed, (k, v) => v === undefined ? 0 : v)

    
    console.log(result)

CodePudding user response:

maybe like this:

let zed = [
    { name: 'tom', stat1: undefined, stat2: 3 },
    { name: 'nic', stat1: undefined, stat2: undefined },
    { name: 'joe', stat1: 5, stat2: undefined }
];
for(let k_arr in zed){
    for(let k_obj in zed[k_arr]){
        if(zed[k_arr][k_obj] === undefined){
            zed[k_arr][k_obj] = 0;
        }
    }
}
console.log(zed);

  • Related