Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add key and Value if the array key does not exists in Javascript

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

like image 331
user3273621 Avatar asked Sep 05 '25 17:09

user3273621


1 Answers

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

like image 143
Satpal Avatar answered Sep 07 '25 07:09

Satpal