简体   繁体   English

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

[英]how to delete a key from object which has value as undefined

I have a javascript object which has a large amount of key value pairs in it, among them some of the keys have a value as undefined. 我有一个javascript对象,其中包含大量键值对,其中一些键的值未定义。 I what to delete the keys which have the value as undefined. 我该删除具有未定义值的键。

How can I achieve it? 我该如何实现?

With underscore you can use the filter function: 使用下划线,您可以使用过滤器功能:

var data = { a: 1, b: undefined, c: 3};

var noUndefineds = _.filter(data, function(value){
    return value != undefined;
});

or use the reject function with the isUndefined predicate: 或使用带有isUndefined谓词的拒绝函数:

var noUndefineds = _.reject(data, _.isUndefined);

You could do like below: 您可以执行以下操作:

for(var k in obj) { 
  if (typeof obj[k] == 'undefined') { 
    delete obj[k]; 
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM