0

I can copy an object as follows:

var myNew = Object.assign({}, old);

But how do I do this and remove the undefined properties in old? For example:

const old = {1:undefined, 2: "TWO"};
const myNew = {2:"TWO"};
Baz
  • 10,775
  • 30
  • 121
  • 236

1 Answers1

1

You could remove it manually: delete old['1']

Or create a method to do that for an unlimited number of keys.

var old = prune(old);

function prune(obj) {
  var newObj = Object.assign({}, old);
  for(var key in newObj) {
    if(newObj[key] === undefined) {
      delete newObj[key];
    }
  }
  return newObj;
}
therobinkim
  • 2,217
  • 10
  • 19
  • You'd probably want `delete myNew["1"]` to delete the key from the new object, rather than modifying the old one – CodingIntrigue Dec 19 '16 at 09:44
  • @CodingIntrigue Ah yes, good point! ..I forgot to finish my code snippet earlier for some reason, but it's fixed now. Thanks! – therobinkim Dec 19 '16 at 09:48