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.

Mariusz
  • 334
  • 4
  • 16
  • `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" – Jamiec Feb 11 '15 at 14:20
  • Thanks for letting me know – Mariusz Feb 11 '15 at 14:29

2 Answers2

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 = "";
} 
Amit Joki
  • 53,955
  • 7
  • 67
  • 89
  • 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 – Mariusz Feb 11 '15 at 14:45
  • sorry for a long wait, I found this question and figured out I should give you "best answer" Thanks for help :) – Mariusz Mar 12 '15 at 09:09
0

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

"weapon" in equippedItems

or

equippedItems.hasOwnProperty("weapon")
Chris Charles
  • 4,266
  • 15
  • 29
  • 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 – Mariusz Feb 11 '15 at 14:40