Convert undefined keys to null using array.reduce()

Convert undefined keys to null using array.reduce()

Β·

2 min read

Hi πŸ‘‹

Objective : Convert the undefined keys of an object to null without mutating the original object.

Focus : Usage of array reduce method.

Lets take the below object as our target -

const testObject = {
name: 'example',
age: '',
address : '',
city: '',
pin: 404,
website: '',
landmark: 'Near For Loop Market',
state: '',
country: '',
};
const processedObject = Object.keys(testObject).reduce((ourNewObject,currentkey)=>({
...ourNewObject,
[currentkey]: testObject[currentkey] ? testObject[currentkey] : null
}),{});

console.log(processedObject)

So, whats going on here πŸ€”

I bet you must have seen the example of reduce being used for adding array elements i.e calculating the total sum.

On baselines, we are doing the same thing.

array.reduce(callBackFn(accumulator, currentValue),initialValue)

We initialized our reduce method with an empty object, where we accumulated our keys (currentkey) using spread operator in order to avoid replacing the object (ourNewObject) and set the value conditionally there using the ternary operator.

// output
{
name: 'example',
age: null,
address : null,
city: null,
pin: 404,
website: null,
landmark: 'Near For Loop Market',
state: null,
country: null,
};

It it rightly said that array.reduce is the least used but most powerful of the 4 mighty array methods in javascript. It can even single handedly perform the combined functionality of filter and map. Pretty cool isn't it 🀩

Thanks for your time, see you in the other blog πŸ“–

🎐Always remember, we are what we share