-
喵喵时光机
你可以遍历对象: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; // truetest.test1 == null; // truetest.notaprop === null; // falsetest.notaprop == null; // truetest.notaprop === undefined; // truetest.notaprop == undefined; // true
-
茅侃侃
使用一些ES6 / ES2015:1)一个简单的单行内容删除内联项目而不分配:Object.keys(myObj).forEach((key) => (myObj[key] == null) && delete myObj[key]);jsbin2)这个例子被删除了......3)作为函数编写的第一个示例:const removeEmpty = obj => {
Object.keys(obj).forEach(key => obj[key] == null && delete obj[key]);};jsbin4)此函数也使用递归来从嵌套对象中删除项目: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
});};jsbin4b)这类似于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.
{}
);jsbin6)与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]})5b) 使用递归并使用ES2019返回新对象的另一个功能版本 : Object.fromEntries()const removeEmpty = obj =>
Object.fromEntries(
Object.entries(obj)
.filter(([k, v]) => v != null)
.map(([k, v]) => (typeof v === "object" ? [k, removeEmpty(v)] : [k, v]))
);7)与4)相同,但在简单的ES5中:function removeEmpty(obj) {
Object.keys(obj).forEach(function(key) {
if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key])
else if (obj[key] == null) delete obj[key]
});};jsbin
-
手掌心
如果您使用的是lodash或underscore.js,这是一个简单的解决方案:var obj = {name: 'John', age: null};var compacted = _.pickBy(obj);这只适用于lodash 4,pre lodash 4或underscore.js,使用_.pick(obj, _.identity);