4

I want to create a dictionary in JavaScript by checking for the objects property.

   var item = {};
   if(item.hasOwnProperty("xyz")){
       //do wat is required
   }else{
       //add the key property to the item object
   }

How to add this "xyz" key property to the object is my question.

Thanks

0

4 Answers 4

5

You just need to use item.xyz='Whatever' and xyz will be added to item

var item = {};
if (item.hasOwnProperty('xyz')) {
    console.log('item has xyz');
} else {
    item.xyz = 'something';
    //item["xyz"] = 'something'; You can also use this
}
console.log(item);

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

what if item.xyz equals to 0 or false or null, in these cases item.xyz exists, but it will be treated like when that is not exists
2

if you need to assign that, there is no need to any check:

item["xyz"] = "something";

if xyz exists on item, it will be assigned else it will be created

Comments

1

Just do item.xyz and assign whatever you want to that.

item.xyz = 'abc';

Then you can just check for item.xyz

Comments

0
  var item = {};
   if(item.hasOwnProperty("xyz")) {
       alert('Item has already that property');
   } else {
      item.xyz= value;
   }

2 Comments

what if item.xyz equals to 0 or false or null, in these cases item.xyz exists, but it will be treated like when that is not exists
you are right. I have corrected my answer. thanks for suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.