To return only non-null values of object properties in an object array, you can use a combination of Array.prototype.map()
and Object.entries()
. Here's a step-by-step guide:
Assuming you have an array of objects like this:
javascriptconst data = [
{ id: 1, name: 'John', age: 25, address: null },
{ id: 2, name: 'Alice', age: null, address: '123 Main St' },
{ id: 3, name: null, age: 30, address: '456 Park Ave' },
{ id: 4, name: 'Bob', age: 35, address: '789 Elm St' },
];
Step 1: Use Array.prototype.map()
to iterate over the array.
Step 2: For each object in the array, use Object.entries()
to get an array of key-value pairs.
Step 3: Use Array.prototype.reduce()
to filter out the non-null values.
Step 4: Create a new object with the filtered key-value pairs.
Step 5: Return the filtered object for each element in the resulting array.
javascriptconst filteredData = data.map((obj) => {
return Object.entries(obj).reduce((acc, [key, value]) => {
if (value !== null) {
acc[key] = value;
}
return acc;
}, {});
});
console.log(filteredData);
Output:
javascript[
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Alice', address: '123 Main St' },
{ id: 3, age: 30, address: '456 Park Ave' },
{ id: 4, name: 'Bob', age: 35, address: '789 Elm St' },
]
Now, filteredData
contains the array of objects with only non-null values of object properties. It removes properties that have a value of null
.