Skip to content

Instantly share code, notes, and snippets.

@harishtocode
Created April 4, 2023 09:16
Show Gist options
  • Save harishtocode/0920ce06d6c1e419a3eef183d112728e to your computer and use it in GitHub Desktop.
Save harishtocode/0920ce06d6c1e419a3eef183d112728e to your computer and use it in GitHub Desktop.
remove null properties from a nested json object
/*Remove null properties from a nested json object*/
function parse(input) {
if (
input == null ||
(Array.isArray(input) && input.length == 0) ||
JSON.stringify(input) == "{}"
) {
return null;
}
if (typeof input === "object" && Array.isArray(input) == false) {
let result = null;
Object.keys(input).forEach((key) => {
const value = parse(input[key]);
if (value != null) {
result = result || {};
result[key] = value;
}
});
return result;
} else if (Array.isArray(input)) {
if (input.length > 0) {
const a = [];
input.forEach((e) => {
const v = parse(e);
if (v != null) a.push(v);
});
return a;
} else return null;
} else return input;
}
const person = {
name: "John",
age: 30,
married: true,
retired: false,
kids: ["Ann", "Billy"],
dogs: null,
cats: 0,
properties: { homes: [], rentals: [] },
cars: [
{ model: "BMW 230", mpg: 27.5, vin: "", manual: false },
{ model: "Ford Edge", mpg: 24.1, features: [] },
[{ model: "Tesla Model S", mpg: null }],
[null, ""],
false,
null,
],
};
const out = parse(person);
console.log(out);
// {
// name: "John",
// age: 30,
// married: true,
// retired: false,
// kids: ["Ann", "Billy"],
// cats: 0,
// cars: [
// { model: "BMW 230", mpg: 27.5, vin: "", manual: false },
// { model: "Ford Edge", mpg: 24.1 },
// [{ model: "Tesla Model S" }],
// [""],
// false,
// ],
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment