How I can filter the object in array that is missing some keys. Here is the explanation:
For example, I have a array of objects:
const array = [
{
a: 1,
b: 2,
c: 3,
d: 4
},
{
b: 6,
c: 9,
d: 10
},
{
b: 5,
c: 7,
d: 10
}
]
As we see that, there are 2 objects that missing "a" property. How I can filter and add the "a" property with value for the missing key object?
Thank you so much, and have a nice day!
>Solution :
You could use javascript’s filter function. Then, you could use map to iterate those objects without a and, with a spread operator, add just the a property to it, if you want a separate array with only the objects where A is missing. However, the cleanest way, if you want the same array, just adding the a property where it is missing, is to map the array and just add the property where it needs to be added.
const array = [{
a: 1,
b: 2,
c: 3,
d: 4
},
{
b: 6,
c: 9,
d: 10
},
{
b: 5,
c: 7,
d: 10
}
]
//Long version, just to show you the main idea
const filteredArray = array.filter((obj) => (obj.a === undefined));
console.log(filteredArray)
const filteredArrayWithAddedValues = filteredArray.map((obj) => ({ ...obj,
a: 100
}));
console.log(filteredArrayWithAddedValues)
//Short version, if you want the same array just adding the A property where is missing
const masterArray = array.map((obj) => {
if (obj.a !== undefined) return obj;
return { ...obj,
a: 100
}
});
console.log(masterArray)