如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
如果你不想修改原始对象(使用一些ES6操作符):
const keys = Object.keys(objectWithNulls).filter(key => objectWithNulls[key]);
const pairs = keys.map(key => ({ [key]: objectWithNulls[key] }));
const objectWithoutNulls = pairs.reduce((val, acc) => ({ ...val, ...acc }));
过滤器(key => objectWithNulls[key])返回任何为真值的值,因此将拒绝任何值,如0或false,以及undefined或null。可以很容易地更改为过滤器(key => objectWithNulls[key] !== undefined)或类似的东西,如果这是不想要的行为。
其他回答
如果你可以使用Lodash,你可以添加DeepDash递归库,并实现你想要的一些非常简洁的代码:
const prune = obj => _.filterDeep(obj, (v) => !(_.isUndefined(v) || _.isNull(v)));
调用prune(anObjectWithNulls)将返回没有未定义或空值的对象。
你可以使用空合并运算符:??因为它只检查空值和未定义值。注意,下面的例子改变了obj本身。它还删除嵌套对象的空值和未定义值。
const removeEmptyKeys = (obj) => {
Object.entries(obj).forEach(([k, v]) => {
(v ?? delete obj[k])
if (v && typeof v === 'object') {
removeEmptyKeys(v)
}
})
}
下面是一个使用ES6从对象中删除null值的函数式方法,而不需要只使用reduce来改变对象:
const stripNulls = (obj) => {
return Object.keys(obj).reduce((acc, current) => {
if (obj[current] !== null) {
return { ...acc, [current]: obj[current] }
}
return acc
}, {})
}
您可以使用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例子
您可能正在寻找delete关键字。
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;