如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
清洁物体到位
// General cleanObj function
const cleanObj = (valsToRemoveArr, obj) => {
Object.keys(obj).forEach( (key) =>
if (valsToRemoveArr.includes(obj[key])){
delete obj[key]
}
})
}
cleanObj([undefined, null], obj)
纯函数
const getObjWithoutVals = (dontReturnValsArr, obj) => {
const cleanObj = {}
Object.entries(obj).forEach( ([key, val]) => {
if(!dontReturnValsArr.includes(val)){
cleanObj[key]= val
}
})
return cleanObj
}
//To get a new object without `null` or `undefined` run:
const nonEmptyObj = getObjWithoutVals([undefined, null], obj)
其他回答
你也可以用…使用forEach扩展语法,如下所示:
设 obj = { a: 1, b: “b”, c: undefined, d: null }; let cleanObj = {}; Object.keys(obj).forEach(val => { const newVal = obj[val]; cleanObj = newVal ?{ ...cleanObj, [val]: newVal } : cleanObj; }); console.info(清洁对象);
递归地删除null, undefined,空对象和空数组,返回一个副本(ES6版本)
export function skipEmpties(dirty) {
let item;
if (Array.isArray(dirty)) {
item = dirty.map(x => skipEmpties(x)).filter(value => value !== undefined);
return item.length ? item : undefined;
} else if (dirty && typeof dirty === 'object') {
item = {};
Object.keys(dirty).forEach(key => {
const value = skipEmpties(dirty[key]);
if (value !== undefined) {
item[key] = value;
}
});
return Object.keys(item).length ? item : undefined;
} else {
return dirty === null ? undefined : dirty;
}
}
如果有人需要欧文(和埃里克)答案的递归版本,这里是:
/**
* 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);
}
}
}
您可以使用JSON的组合。stringify,它的替换参数,以及JSON。解析将其转换回对象。使用此方法还意味着替换嵌套对象中的所有嵌套键。
实例对象
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例子
更短的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