如何删除这些都是属性undefined
或null
在JavaScript对象?
(问题类似于这个阵列)
使用一些ES6/ES2015:
1)一个简单的单行内容删除内联项目而不分配:
Object.keys(myObj).forEach((key) => (myObj[key] == null) && delete myObj[key]);
jsbin
2)这个例子被删除了......
3)作为函数编写的第一个示例:
const removeEmpty = obj => { Object.keys(obj).forEach(key => obj[key] == null && delete obj[key]); };
jsbin
4)此函数也使用递归来从嵌套对象中删除项目:
const removeEmpty = obj => { Object.keys(obj).forEach(key => { if (obj[key] && typeof obj[key] === "object") removeEmpty(obj[key]); // recurse else if (obj[key] == null) delete obj[key]; // delete }); };
jsbin
4b)这类似于4),但它不是直接改变源对象,而是返回一个新对象.
const removeEmpty = obj => { const newObj = {}; Object.keys(obj).forEach(key => { if (obj[key] && typeof obj[key] === "object") { newObj[key] = removeEmpty(obj[key]); // recurse } else if (obj[key] != null) { newObj[key] = obj[key]; // copy value } }); return newObj; };
5)基于@ MichaelJ.Zoidl的回答使用和的4b)的功能方法.这个也返回一个新对象:filter()
reduce()
const removeEmpty = obj => Object.keys(obj) .filter(k => obj[k] != null) // Remove undef. and null. .reduce( (newObj, k) => typeof obj[k] === "object" ? { ...newObj, [k]: removeEmpty(obj[k]) } // Recurse. : { ...newObj, [k]: obj[k] }, // Copy value. {} );
jsbin
6)与4)相同,但使用ES7/2016 Object.entries()
.
const removeEmpty = (obj) => Object.entries(obj).forEach(([key, val]) => { if (val && typeof val === 'object') removeEmpty(val) else if (val == null) delete obj[key] })
7)与4)相同,但在简单的ES5中:
const removeEmpty = obj => Object.fromEntries( Object.entries(obj) .filter(([k, v]) => v != null) .map(([k, v]) => (typeof v === "object" ? [k, removeEmpty(v)] : [k, v])) );
jsbin
你可以遍历对象:
var test = { test1 : null, test2 : 'somestring', test3 : 3, } function clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } } clean(test);
如果您担心此属性删除没有运行对象的proptype链,您还可以:
function clean(obj) { var propNames = Object.getOwnPropertyNames(obj); for (var i = 0; i < propNames.length; i++) { var propName = propNames[i]; if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } }
关于null vs undefined的一些注释:
test.test1 === null; // true test.test1 == null; // true test.notaprop === null; // false test.notaprop == null; // true test.notaprop === undefined; // true test.notaprop == undefined; // true
如果您使用的是lodash或underscore.js,这是一个简单的解决方案:
var obj = {name: 'John', age: null}; var compacted = _.pickBy(obj);
这只适用于lodash 4,pre lodash 4或underscore.js,使用_.pick(obj, _.identity)
;
如果有人需要Owen(和Eric的)答案的递归版本,这里是:
/** * Delete all null (or undefined) properties from an object. * Set 'recurse' to true if you also want to delete properties in nested objects. */ function delete_null_properties(test, recurse) { for (var i in test) { if (test[i] === null) { delete test[i]; } else if (recurse && typeof test[i] === 'object') { delete_null_properties(test[i], recurse); } } }
ES6 +的最短衬管
过滤所有伪造的值(“”,0,false,null,undefined)
Object.entries(obj).reduce((a,[k,v]) => (v ? {...a, [k]:v} : a), {})
过滤null和undefined值:
Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : {...a, [k]:v}), {})
仅过滤null
Object.entries(obj).reduce((a,[k,v]) => (v === null ? a : {...a, [k]:v}), {})
筛选器未定义
Object.entries(obj).reduce((a,[k,v]) => (v === undefined ? a : {...a, [k]:v}), {})
递归:过滤null和undefined
const cleanEmpty = obj => Object.entries(obj) .map(([k,v])=>[k,v && typeof v === "object" ? cleanEmpty(v) : v]) .reduce((a,[k,v]) => (v == null ? {...a, [k]:v} : a), {});
JSON.stringify删除未定义的键.
removeUndefined = function(json){ return JSON.parse(JSON.stringify(json)) }
您可能正在寻找delete
关键字.
var obj = { }; obj.theProperty = 1; delete obj.theProperty;
您可以使用JSON.stringify
其replacer参数的组合,并将JSON.parse
其重新转换为对象.使用此方法还意味着替换嵌套对象中的所有嵌套键.
示例对象
var exampleObject = { string: 'value', emptyString: '', integer: 0, nullValue: null, array: [1, 2, 3], object: { string: 'value', emptyString: '', integer: 0, nullValue: null, array: [1, 2, 3] }, arrayOfObjects: [ { string: 'value', emptyString: '', integer: 0, nullValue: null, array: [1, 2, 3] }, { string: 'value', emptyString: '', integer: 0, nullValue: null, array: [1, 2, 3] } ] };
替换功能
function replaceUndefinedOrNull(key, value) { if (value === null || value === undefined) { return undefined; } return value; }
清理对象
exampleObject = JSON.stringify(exampleObject, replaceUndefinedOrNull); exampleObject = JSON.parse(exampleObject);
CodePen示例
Lodash解决方案最简单的解决方案,可返回过滤出null
和undefined
值的对象。
_.omitBy(obj, _.isNil)
Functional and immutable approach, without .filter
and without creating more objects than needed
Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})
使用ramda#pickBy你会删除所有null
,undefined
和false
值:
const obj = {a:1, b: undefined, c: null, d: 1} R.pickBy(R.identity, obj)
正如@manroe所指出的,要保留false
值,请使用isNil()
:
const obj = {a:1, b: undefined, c: null, d: 1, e: false} R.pickBy(v => !R.isNil(v), obj)
更短的ES6纯解决方案,将其转换为数组,使用过滤功能并将其转换回对象.也很容易做一个功能......
顺便说一句.用这个.length > 0
我检查是否有一个空字符串/数组,所以它将删除空键.
const MY_OBJECT = { f: 'te', a: [] } Object.keys(MY_OBJECT) .filter(f => !!MY_OBJECT[f] && MY_OBJECT[f].length > 0) .reduce((r, i) => { r[i] = MY_OBJECT[i]; return r; }, {});
JS BIN https://jsbin.com/kugoyinora/edit?js,console