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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27709636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:31:52  来源:igfitidea点击:

Determining if all attributes on a javascript object are null or an empty string

javascriptobjectattributes

提问by J-bob

What is the most elegant way to determine if all attributes in a javascript object are either null or the empty string? It should work for an arbitrary number of attributes.

确定 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

回答by PVermeer

Edit:As user @abd995 noted in the comments, using Array.some() is more effici?nt as it stops the loop when the condition is met:

编辑:正如用户@abd995 在评论中指出的那样,使用 Array.some() 更有效,因为它在满足条件时停止循环:

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

Original:2017 answer: Check all values with Object.values(). Returns an array with the values which you can check with Array.every() or Array.some()... etc.

原文:2017 答案:使用 Object.values() 检查所有值。返回一个包含值的数组,您可以使用 Array.every() 或 Array.some()... 等检查这些值。

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

回答by tymeJV

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

回答by adeneo

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
    });
}

回答by whirmill

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

您可以在对象的键上使用 Array.reduce 原型。

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:

如果你想发现它的所有属性是否都被设置了,你必须在条件之前删除否定,并且只有当对象有键时才将初始结果值设置为 true:

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

回答by deamon

Using Array.some()and check if the values are not nulland not emptyis more efficientthan using Array.everyand check it the other way around.

使用Array.some()和检查值不null,不empty就是更有效比使用Array.every和周围检查它的其他方式。

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

This answer should just make the excellent commentof user abd995more visible.

这个答案应该只是让用户abd995的优秀评论更加明显。

回答by ajilpm

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

根据adeneo的回答,我创建了一个单行条件。希望它会对某人有所帮助。

var test = {
  "email": "[email protected]",
  "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/

你可以测试一下https://jsfiddle.net/4uyue8tk/2/

回答by Jayanga Jayathilake

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

回答by Luis García

Based on tymeJv's answer =)

基于 tymeJv 的回答 =)

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 =)

希望它有帮助 =)

回答by Bruno Ribeiro

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 allits values (and values inside values) are undefined, {}or [].

所以我想出了这个解决方案。如果对象的所有值(以及值中的值)都是undefined,{}或,则它会将对象评估为空[]

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 '_'.

请注意,.isEmpty()在我们“隔离”一个值后,它使用 Lodash来完成繁重的工作。在这里,Lodash 被导入为“_”。

Hope it helps!

希望能帮助到你!

回答by mkapiczy

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

在其他答案的基础上,我将使用 lodash 检查isEmpty对象及其属性。

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