如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
您可能正在寻找delete关键字。
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
其他回答
清洁物体到位
// 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)
使用ramda#pickBy你将删除所有null, undefined和false值:
const obj = {a:1, b: undefined, c: null, d: 1}
R.pickBy(R.identity, obj)
正如@manroe指出的,要保留假值,请使用isNil():
const obj = {a:1, b: undefined, c: null, d: 1, e: false}
R.pickBy(v => !R.isNil(v), obj)
这可以使用递归来解决。JavaScript对象可以是一个数组,也可以有一个包含空值的数组作为值。
function removeNullValues(obj) {
// Check weather obj is an array
if (Array.isArray(obj)) {
// Creating copy of obj so that index is maintained after splice
obj.slice(0).forEach((val) => {
if (val === null) {
obj.splice(obj.indexOf(val), 1);
} else if (typeof val === 'object') {
// Check if array has an object
removeNullValues(val);
}
});
} else if (typeof obj === 'object') {
// Check for object
Object.keys(obj).forEach((key) => {
if (obj[key] === null) {
delete obj[key];
} else if (typeof obj[key] === 'object') {
removeNullValues(obj[key]);
}
});
}
return obj;
}
如果有人需要欧文(和埃里克)答案的递归版本,这里是:
/**
* 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);
}
}
}
清除空数组、空对象、空字符串、未定义、NaN和空值。
function objCleanUp(obj:any) {
for (var attrKey in obj) {
var attrValue = obj[attrKey];
if (attrValue === null || attrValue === undefined || attrValue === "" || attrValue !== attrValue) {
delete obj[attrKey];
} else if (Object.prototype.toString.call(attrValue) === "[object Object]") {
objCleanUp(attrValue);
if(Object.keys(attrValue).length===0)delete obj[attrKey];
} else if (Array.isArray(attrValue)) {
attrValue.forEach(function (v,index) {
objCleanUp(v);
if(Object.keys(v).length===0)attrValue.splice(index,1);
});
if(attrValue.length===0)delete obj[attrKey];
}
}
}
objCleanUp(myObject)
(attrValue !== attrValue)检查NaN。在这里学的