确定 javascript 对象上的所有属性是 null 还是空字符串

确定 javascript 对象中的所有属性是 null 还是空字符串的最佳方法是什么?它应该适用于任意数量的属性。

{'a':null, 'b':''} //should return true for this object
{'a':1, 'b':''} //should return false for this object
{'a':0, 'b':1} //should return false
{'a':'', 'b':''} //should return true
167619 次浏览

Create a function to loop and check:

function checkProperties(obj) {
for (var key in obj) {
if (obj[key] !== null && obj[key] != "")
return false;
}
return true;
}


var obj = {
x: null,
y: "",
z: 1
}


checkProperties(obj) //returns false

Here's my version, specifically checking for null and empty strings (would be easier to just check for falsy)

function isEmptyObject(o) {
return Object.keys(o).every(function(x) {
return o[x]===''||o[x]===null;  // or just "return o[x];" for falsy values
});
}

Based on tymeJv's answer =)

function checkProperties(obj) {
var state = true;
for (var key in obj) {
if ( !( obj[key] === null || obj[key] === "" ) ) {
state = false;
break;
}
}
return state;
}


var obj = {
x: null,
y: "",
z: 1
}


checkProperties(obj) //returns false

Hope it helps =)

Based on adeneo's answer, I created a single line condition. Hope it will be helpful to someone.

var test = {
"email": "test@test.com",
"phone": "1234567890",
"name": "Test",
"mobile": "9876543210",
"address": {
"street": "",
"city": "",
"state": "",
"country": "",
"postalcode": "r"
},
"website": "www.test.com"
};


if (Object.keys(test.address).every(function(x) { return test.address[x]===''||test.address[x]===null;}) === false) {
console.log('has something');
} else {
console.log('nothing');
}

You can test it https://jsfiddle.net/4uyue8tk/2/

You can use the Array.reduce prototype on your object's keys.

Assuming that the object is structured as follows:

var obj = {
x: null,
y: "",
z: 1
}

you can use the following instruction to discover if all of it's properties are unset or set to empty string using just one line:

Object.keys(obj).reduce((res, k) => res && !(!!obj[k] || obj[k] === false || !isNaN(parseInt(obj[k]))), true) // returns false

If you want to discover if all of it's properties are set instead you have to remove the negation before the conditions and set the initial result value to true only if the object has keys:

Object.keys(obj).reduce((res, k) => res && (!!obj[k] || obj[k] === false || !isNaN(parseInt(obj[k]))), Object.keys(obj).length > 0) // returns false as well

Check all values with Object.values. It returns an array with the values, which you can check with Array.prototype.every or Array.prototype.some:

const isEmpty = Object.values(object).every(x => x === null || x === '');
const isEmpty = !Object.values(object).some(x => x !== null && x !== '');

This skip the function attribute

function checkIsNull(obj){
let isNull=true;
for(let key in obj){
if (obj[key] && typeof obj[key] !== 'function') {
isNull = false;
}
}
return isNull;
}


var objectWithFunctionEmpty={
"name":undefined,
"surname":null,
"fun": function (){ alert('ciao'); }
}


var objectWithFunctionFull={
"name":undefined,
"surname":"bla bla",
"fun": function (){ alert('ciao'); }
}


checkIsNull(objectWithFunctionEmpty); //true
checkIsNull(objectWithFunctionFull); //false

Just complementing the past answers: they'll work if your object doesn't contain arrays or objects. If it does, you'll need to do a 'deep check'.

So I came up with this solution. It'll evaluate the object as empty if all its values (and values inside values) are undefined, {} or [].

function deepCheckEmptyObject(obj) {
return Object.values(obj).every( value => {
if (value === undefined) return true;
else if ((value instanceof Array || value instanceof Object) && _.isEmpty(value) ) return true;
else if (value instanceof Array && !_.isEmpty(value)) return deepCheckEmptyArray(value);
else if (value instanceof Object && !_.isEmpty(value)) return deepCheckEmptyObject(value);
else return false;
});
}


function deepCheckEmptyArray(array) {
return array.every( value => {
if (value === undefined) return true;
else if ((value instanceof Array || value instanceof Object) && _.isEmpty(value)) return true;
else if (value instanceof Array && !_.isEmpty(value)) return deepCheckEmptyArray(value);
else if (value instanceof Object && !_.isEmpty(value)) return deepCheckEmptyObject(value);
else return false;
});
}

Note it uses Lodash's .isEmpty() to do the heavy work after we 'isolated' a value. Here, Lodash is imported as '_'.

Hope it helps!

Building on top of other answers I would use lodash to check isEmpty on the object, as well as its properties.

const isEmpty = (object) => return _.isEmpty(object) || !Object.values(object).some(x => !_.isEmpty(x))

This will give you all the keys from the object which is empty, undefined and null

Object.keys(obj).filter((k)=> {
if (obj[k] === "" || obj[k]===undefined || obj[k]===null) {
return k;
}
});

This works with me perfectly:

checkProperties(obj) {
let arr = [];
for (let key in obj) {
arr.push(obj[key] !== undefined && obj[key] !== null && obj[key] !== "");
}
return arr.includes(false);
}

This will return true or false if there is at-least one value is empty or something like that.

You can use Object.values() method to get all the object's values (as an array of object's values) and then check if this array of values contains null or "" values, with the help of _.includes method prvided by lodash library.

const checkObjectProperties = obj => {
const objValues = Object.keys(obj);


if (_.includes(objValues, "") || _.includes(objValues, null)) {
return false;
} else {
return true
}
  

const incorrectObjProps = { one: null, two: "", three: 78 }
const correctObjProps = { one: "some string" }
  

checkObjectProperties(incorrectObjProps) // return false
checkObjectProperties(correctObjProps) // return true
}

Using Array.some() and check if the values are not null and not empty is more efficient than using Array.every and check it the other way around.

const isEmpty = !Object.values(object).some(x => (x !== null && x !== ''));

This answer should just make the excellent comment of user abd995 more visible.

Also if you are searching for only values are empty within the object,

Object.values({ key: 0, key2: null, key3: undefined, key4: '' }).some(e => Boolean(e))
// false


Object.values({ key: 0, key2: null, key3: undefined, key4: "hello" }).some(e => Boolean(e))
// true


Object.values({ key: 1, key2: "hello" }).some(e => Boolean(e))
// true
let obj = { x: null, y: "hello", z: 1 };
let obj1 = { x: null, y: "", z: 0 };


!Object.values(obj).some(v => v);
// false


!Object.values(obj1).some(v => v);
// true

I'll add my two sense:

Object.values(object).every(value => Boolean(value));

Solution:

function checkValues(obj) {
var objValues = Object.values(obj);
if (objValues.length < 1) return false;
return objValues.every((value) => {
if (value === null) return true;
if (typeof(value) == 'string')
if(!(value || false))
return true;
return false;
});
}
// OR
Object.values( obj ).every(
value => value === null || (typeof(value) == 'string' && !(value || false))
);

Testing:

checkValues({ a: null, b: '' });
// OR
Object.values({ a: null, b: '' }).every(
value => value === null || (typeof(value) == 'string' && !(value || false))
);
// Output: true


checkValues({ a: '', b: '' });
// OR
Object.values({ a: '', b: '' }).every(
value => value === null || (typeof(value) == 'string' && !(value || false))
);
// Output: true


checkValues({ a: 0, b: '' });
// OR
Object.values({ a: 0, b: '' }).every(
value => value === null || (typeof(value) == 'string' && !(value || false))
)
// Output: false


checkValues({ a: 0, b: 1 });
// OR
Object.values({ a: 0, b: 1 }).every(
value => value === null || (typeof(value) == 'string' && !(value || false))
)
// Output: false


checkValues({ a: 1, b: '' });
// OR
Object.values({ a: 1, b: '' }).every(
value => value === null || (typeof(value) == 'string' && !(value || false))
)
// Output: false

How about this?

!Object.values(yourObject).join('')

Quick and simple solution:

Object.values(object).every(value => !!value);