How to Remove Null Objects from Nested Array of objects in JavaScript ?
Last Updated :
01 Feb, 2024
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed.
There are various approaches to Remove Null Objects from a Nested Array of objects in JavaScript
Using every Method
Every method is used to iterate through each level of the nested array. At each level, every method checks if all elements pass a specified condition, excluding null objects, effectively filtering them out.
Syntax:
array.every(callback(element, index, array), thisArg)
Example: The below code uses every method to Remove Null Objects from a Nested Array of objects in JavaScript.
Javascript
let arr = [
{ id: 1, values: [1, 2, 3] },
{ id: 2, values: [ null , 5, 6] },
{ id: 3, values: [7, 8, 9] },
{ id: 4, values: [10, null , 12] },
];
let output = arr.filter((obj) => {
return obj.values.every((value) => {
return value !== null ;
});
});
console.log(output);
|
Output
[ { id: 1, values: [ 1, 2, 3 ] }, { id: 3, values: [ 7, 8, 9 ] } ]
Using includes Method
Include method is used to filter out null objects from a nested array. By recursively applying includes to each level of the nested structure, null objects are excluded from the resulting array.
Syntax:
array.includes(searchElement, fromIndex)
Example: The below code uses includes a method to Remove Null Objects from a Nested Array of objects in JavaScript.
Javascript
let arr = [
{ id: 1, values: [1, 2, 3] },
{ id: 2, values: [ null , 5, 6] },
{ id: 3, values: [7, 8, 9] },
{ id: 4, values: [10, null , 12] },
];
let output = arr.filter((obj) => {
return !obj.values.includes( null );
});
console.log(output);
|
Output
[ { id: 1, values: [ 1, 2, 3 ] }, { id: 3, values: [ 7, 8, 9 ] } ]
Using reduce Method
This approach uses the reduce method to recursively filter out null objects from a nested array of objects. The reduce function accumulates the non-null objects while traversing through each level of the nested structure.
Syntax:
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
Example: The below code uses a reduce method to Remove Null Objects from a Nested Array of objects in JavaScript.
Javascript
let arr = [
{ id: 1, values: [1, 2, 3] },
{ id: 2, values: [ null , 5, 6] },
{ id: 3, values: [7, 8, 9] },
{ id: 4, values: [10, null , 12] },
];
let output = arr.reduce((acc, obj) => {
if (!obj.values.includes( null )) {
acc.push({ ...obj });
}
return acc;
}, []);
console.log(output);
|
Output
[ { id: 1, values: [ 1, 2, 3 ] }, { id: 3, values: [ 7, 8, 9 ] } ]
Share your thoughts in the comments
Please Login to comment...