w2olves w2olves - 3 months ago 18
Javascript Question

Look through an array of objects and remove undefined from its property

I have an array of objects, I would like to remove 'undefined' from any of the properties in any of the objects.

To remove undefined from an object, I use this method,

removeNullorUndefined:function(model) {
function recursiveFix(o) {
// loop through each property in the provided value
for (var k in o) {
// make sure the value owns the key
if (o.hasOwnProperty(k)) {
if (o[k] === 'undefined') {
// if the value is undefined, set it to 'null'
o[k] = '';
} else if (typeof (o[k]) !== 'string' && o[k].length > 0) {
// if there are sub-keys, make a recursive call
recursiveFix(o[k]);
}
}
}
}

var cloned = $.extend(true, {}, model);
recursiveFix(cloned);
return cloned;

},


How can I modify this so it can also accept an array of objects and remove 'undefined' from it ?

Appreciate any inputs

Answer

As long as the value is undefined and not a string value of 'undefined' then one way is to use JSON.stringify. Referring to property values:

If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).

So, you could stringify an object and immediately parse it to remove undefined values.

NOTE: This approach will deep clone the entire object. In other words if references need to be maintained this approach won't work.

var obj = {
  foo: undefined,
  bar: ''
};
var cleanObj = JSON.parse(JSON.stringify(obj));

// For dispaly purposes only
document.write(JSON.stringify(cleanObj, null, 2));

An added bonus is without any special logic it will work at any depth:

var obj = {
  foo: {
    far: true,
    boo: undefined
  },
  bar: ''
};
var cleanObj = JSON.parse(JSON.stringify(obj));

// For dispaly purposes only
document.write(JSON.stringify(cleanObj, null, 2));

If it is a string value of 'undefined' you can use the same approach but with a replacer function:

var obj = {
  foo: {
    far: true,
    boo: 'undefined'
  },
  bar: ''
};
var cleanObj = JSON.parse(JSON.stringify(obj, replacer));

function replacer(key, value) {
  if (typeof value === 'string' && value === 'undefined') {
    return undefined;
  }

  return value;
}

// For dispaly purposes only
document.write(JSON.stringify(cleanObj, null, 2));

Comments