如何删除对象中未定义的键和值?

时间:2019-05-22 14:52:54

标签: javascript javascript-objects

如何从对象中删除undefined的键和值?

例如我有

var x = {
 firstname: undefined,
 lastname: 'blabla'
}

如何获取没有未定义的对象?以最有效,最快捷的方式?

结果应为:

x = {
 lastname: 'blabla'
}

1 个答案:

答案 0 :(得分:1)

var x = {
 firstname: undefined,
 lastname: 'blabla'
}

for (let key in x) {
  if (x[key] === undefined) {
   delete x[key];
  }
}