javascript - 检查对象是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42813784/
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
javascript - check if object is empty
提问by dmikester1
I am trying to create to javascript/jquery test to check if my object is empty and cannot figure it out.
我正在尝试创建 javascript/jquery 测试以检查我的对象是否为空并且无法弄清楚。
Here is the object when it has something in it:
这是其中有东西时的对象:
{"mergedSellerArray":{"key1114":"1120"}}
And here is the object when empty:
这是空时的对象:
{"mergedSellerArray":{}}
This is the current test I have based on another SO answer but it does not work:
这是我基于另一个 SO 答案进行的当前测试,但它不起作用:
var sellers = JSON.stringify({mergedSellerArray});
if(Object.keys(sellers).length === 0 && sellers.constructor === Object) {
console.log("sellers is empty!");
}
回答by Weedoze
You were testing sellerswhich is not empty because it contains mergedSellerArray. You need to test sellers.mergedSellerArray
您正在测试sellers哪个不为空,因为它包含mergedSellerArray. 你需要测试sellers.mergedSellerArray
let sellers = {
"mergedSellerArray": {}
};
if (Object.keys(sellers.mergedSellerArray).length === 0 && sellers.mergedSellerArray.constructor === Object) {
console.log("sellers is empty!");
} else {
console.log("sellers is not empty !");
}
回答by sharif2008
Here is in jQuery:
这是在 jQuery 中:
$(document).ready(function(){
var obj={"mergedSellerArray":{}};
alert("is empty: "+$.isEmptyObject(obj.mergedSellerArray));
var obj2={"mergedSellerArray":{"key1114":"1120"}};
alert("is empty: "+$.isEmptyObject(obj2.mergedSellerArray));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
jsfidle: https://jsfiddle.net/nyqgbp38/
jsfiddle: https://jsfiddle.net/nyqgbp38/
回答by Vasuki Dileep
If you are using lodash library, you have an elegant way to check an empty object, array, map or a set. I presume you are aware of ES6 Import statement.
如果你使用 lodash 库,你有一种优雅的方式来检查空对象、数组、映射或集合。我想你知道 ES6 Import 语句。
import {isEmpty} from "lodash"
let obj = {};
console.log(isEmpty(obj)); //Outputs true.
let arr = [];
console.log(isEmpty(arr)); //Outputs true.
obj.name="javascript";
console.log(isEmpty(obj)); //Outputs false.
So, for your code,
所以,对于你的代码,
isEmpty(mergedSellerArray); //will return true if object is not empty.
Hope this answer helped.
希望这个答案有帮助。
回答by Ragnar
Can create the helper function :
可以创建辅助函数:
const isEmpty = inputObject => {
return Object.keys(inputObject).length === 0;
};
Can use it like:
可以像这样使用它:
let inputObject = {};
console.log(isEmpty(inputObject)) // true.
and
和
inputObject = {name: "xyz"};
console.log(isEmpty(inputObject)) // false

