How to Remove Null Objects from Nested Array of objects in JavaScript ?
Last Updated :
16 Jul, 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
// Input arr
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] },
];
// Removing null using every
let output = arr.filter((obj) => {
return obj.values.every((value) => {
return value !== null;
});
});
// Output
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
// Input arr
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] },
];
// Removing null using includes
let output = arr.filter((obj) => {
return !obj.values.includes(null);
});
// Output
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
// Input arr
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] },
];
// Removing null using reduce
let output = arr.reduce((acc, obj) => {
if (!obj.values.includes(null)) {
acc.push({ ...obj });
}
return acc;
}, []);
// Output
console.log(output);
Output[ { id: 1, values: [ 1, 2, 3 ] }, { id: 3, values: [ 7, 8, 9 ] } ]
Using Recursion and filter()
This approach involves defining a recursive function to traverse through the nested array of objects. At each level, the function filters out null objects and recursively calls itself on nested arrays of objects.
JavaScript
function removeNullObjects(arr) {
return arr.filter(obj => {
// If the object is null, remove it
if (obj === null) {
return false;
}
// If the object contains a nested array
if (Array.isArray(obj.values)) {
// Recursively remove null objects from the nested array
obj.values = removeNullObjects(obj.values);
}
// Keep the object if it's not null
return obj.values !== null;
});
}
// Input array
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] }
];
// Output
let output = removeNullObjects(arr);
console.log(output);
Output[
{ id: 1, values: [ 1, 2, 3 ] },
{ id: 2, values: [ 5, 6 ] },
{ id: 3, values: [ 7, 8, 9 ] },
{ id: 4, values: [ 10, 12 ] }
]
Using flatMap() Method
The flatMap() method in JavaScript can be used to remove null objects from a nested array of objects by filtering out objects with null values and flattening the resulting array. It provides a concise and efficient solution for this task.
Syntax:
array.flatMap(callback(currentValue, index, array), thisArg)
Example:
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] },
];
// Removing null using flatMap
let output = arr.map(obj => ({
...obj,
values: obj.values.flatMap(value => value !== null ? [value] : [])
})).filter(obj => obj.values.length > 0);
console.log("Before:", arr);
console.log("After:", output);
OutputBefore: [
{ id: 1, values: [ 1, 2, 3 ] },
{ id: 2, values: [ null, 5, 6 ] },
{ id: 3, values: [ 7, 8, 9 ] },
{ id: 4, values: [ 10, null, 12 ] }
]
After: [
{ id: 1, values: [ 1, 2, 3 ] },
...
Using JSON.stringify() and JSON.parse()
Another approach to removing null objects from a nested array of objects is to leverage JSON.stringify() and JSON.parse(). This method involves converting the array to a JSON string, filtering out null values in the process, and then parsing it back into an array. This approach can be particularly useful for deep nested structures as it simplifies the process of removing null values.
Example:
JavaScript
function removeNulls(obj) {
return JSON.parse(JSON.stringify(obj, (key, value) => {
// Filter out null values
if (value === null) {
return undefined;
}
return value;
}));
}
const nestedArray = [
{ a: 1, b: null, c: [{ d: 2, e: null }, { f: 3 }] },
{ g: null, h: 4, i: { j: 5, k: null } },
null,
[{ l: 6, m: null }, null]
];
const cleanedArray = removeNulls(nestedArray);
console.log(cleanedArray);
Output[
{ a: 1, c: [ [Object], [Object] ] },
{ h: 4, i: { j: 5 } },
null,
[ { l: 6 }, null ]
]
Using forEach Method
The forEach method can be used to iterate through each level of the nested array, removing null objects at each level. This method provides a straightforward way to clean up nested arrays of objects.
Example:
JavaScript
function removeNullObjects(arr) {
const result = [];
arr.forEach(obj => {
if (obj !== null) {
if (Array.isArray(obj.values)) {
obj.values = obj.values.filter(value => value !== null);
}
result.push(obj);
}
});
return result;
}
// Input array
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 = removeNullObjects(arr);
console.log(output);
Output[
{ id: 1, values: [ 1, 2, 3 ] },
{ id: 2, values: [ 5, 6 ] },
{ id: 3, values: [ 7, 8, 9 ] },
{ id: 4, values: [ 10, 12 ] }
]
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read