简体   繁体   中英

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. 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:

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

You could do like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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