Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove all undefined from object of array properties

I’m trying to remove all undefined field value from the following object.
Is there any way to remove all undefined value and get clear object(It means object without any undefined value) without recursive function?

I have tried with lodash something like this

_.transform(obj, function(res, v, k) {
  if (v) res[k] = v;
});

and

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

all I can get succeed object was by doing recursively something like this.

function compactObject(data) {
  return Object.keys(data).reduce(function(accumulator, key) {
    const isObject = typeof data[key] === 'object';
    const value = isObject ? compactObject(data[key]) : data[key];
    const isEmptyObject = isObject && !Object.keys(value).length;
    if (value === undefined || isEmptyObject) {
      return accumulator;
    }

    return Object.assign(accumulator, {[key]: value});
  }, {});
}

However, I would like to make it more simplify. Can any one has good idea of this?

  • Problematic object
var fields = {
    name: "my name",
    note: "my note",
    steps: [
      {action: 'pick', place: {…}, childrenIds: ['_id1', '_id2']},
      {action: 'drop', place: {…}, childrenIds: undefined},
    ],
    email: undefined
}
  • Wanted result
var fields = {
    name: "my name",
    note: "my note",
    steps: [
      {action: 'pick', place: {…}, childrenIds: ['_id1', '_id2']},
      {action: 'drop', place: {…}},
    ],
}

Thank you in advance!

>Solution :

const data = {
    name: "my name",
    note: "my note",
    steps: [
      {action: 'pick', place: {}, childrenIds: ['_id1', '_id2']},
      {action: 'drop', place: {}, childrenIds: undefined},
    ],
    email: undefined
}

function removeUndefined(o) {
  let stack = [o], i;
  while(stack.length) {
    Object.entries(i=stack.pop()).forEach(([k,v])=>{
      if(v===undefined) delete i[k];
      if(v instanceof Object) stack.push(v);
    })
  }
  return o;
}

console.log(removeUndefined(data))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading