0

this is my object . I am trying to remove empty array, empty string,null, undefined.

 let result = {
  a : [],
  b: undefined,
  c: null,
  d: NaN,
  e: {},
  f:{test: undefined, tes1: null,tes2:NaN},
  g:{name :{x:undefined, y:"s", z: null}},
  x:"sujon",
  y:"",
}

Now, I can only delete the undefined value from an object by using this code;

const removeEmpty = (obj) => {
  Object.keys(obj).forEach(key => {
    if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]);
    else if (obj[key] === undefined) delete obj[key];
  });
  return obj;
};

let res = removeEmpty(result) 

console.log(res)

my expected result would be like this:

   let result = {
      g:{name :{y:"s"}},
      x:"sujon",
    }

How can i get my expected result?

  • Does this answer your question? [Remove blank attributes from an Object in Javascript](https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript) – Cully Nov 10 '20 at 05:29

1 Answers1

0

After the recursive call, if the result is an empty object (with no own-properties), remove it:

let result = {
  a : [],
  b: undefined,
  c: null,
  d: NaN,
  e: {},
  f:{test: undefined, tes1: null,tes2:NaN},
  g:{name :{x:undefined, y:"s", z: null}},
  x:"sujon",
  y:"",
  z:0,
}
const removeEmpty = (obj) => {
  Object.keys(obj).forEach(key => {
    if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]);
    if (
      (!obj[key] && obj[key] !== 0) ||
      (typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0)
    ) {
      delete obj[key];
    }
  });
  return obj;
};

let res = removeEmpty(result) 

console.log(res)
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320