Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object inside an object is empty with javascript [duplicate]

Tags:

javascript

Hello I have an object:

var equippedItems = {
weapon: {},
armor: {},
accessory: {}
};

I need a way to check if equippedItems.weapon equals to '' at some point I am doing something like equippedItems.weapon = ''; I dont know if it's exactly the same as above object. I already tried using object.hasOwnProperty but it seems I cannot use equippedItems.weapon in this case, maybe I am doing something wrong? Also note I did read how to check if object is empty already, but it didn't work for my object inside an object.

@Edit:

Like I said, I already read those and they did not give me a straight answer for my question, they did answer how to check if object is empty, but the object was like object = {}; while mine is like object = { object:{}, object2:{}, object3:{}};

Thats why it confuses me.

like image 280
Mariusz Avatar asked Feb 11 '15 14:02

Mariusz


People also ask

Is Empty object Falsy JavaScript?

The empty object is not undefined. The only falsy values in JS are 0 , false , null , undefined , empty string, and NaN .

How do you check if all values in object is empty?

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.

How do you check if an array of objects is empty in JavaScript?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.

How do I check if an object is empty in node JS?

Object. keys(myObj). length === 0; As there is need to just check if Object is empty it will be better to directly call a native method Object.


1 Answers

Just make use of Object.keys

function isEmpty(obj, propName){
   return Object.keys(obj[propName]).length == 0;
}

Another way is to make use of JSON.stringify method which will return {} if empty

function isEmpty(obj, propName){
   return JSON.stringify(obj[propName]) == "{}";
}

In both the cases, you would call the function like

if(isEmpty(equipmentItems.weapons)){
   equipmentItems.weapons = "";
} 
like image 165
Amit Joki Avatar answered Oct 24 '22 07:10

Amit Joki