6

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.

1
  • weapon: {} makes an object with no properties (but an object nonetheless). equippedItems.weapon = '' sets that property to an empty string. They are very much not "exactly the same" Commented Feb 11, 2015 at 14:20

2 Answers 2

5

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 = "";
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, thanks for the answer I will try to implement this and see if this works. If I am not mistaken I should use it like: function isEmpty(equippedItems, weapon){ return Object.keys(equippedItems[weapon]).length == 0; } I am not sure tho -_- i will keep trying
sorry for a long wait, I found this question and figured out I should give you "best answer" Thanks for help :)
0

To check that an object has a property you can use:

"weapon" in equippedItems

or

equippedItems.hasOwnProperty("weapon")

1 Comment

equippedItems has 3 properties which are weapon,armor,accessory. I want to check if weapon/armor/accessory is empty I believe that I already tried your method. I will try it again tho

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.