Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether my key exists in array of object

Tags:

javascript

var arr = [{
   key: "key1", value: "z"
}, {
   key: "key2", value: "u"
}, {
   ...
}];

How to check whether my key:"key1" exists already or not. If it does not exist, i need to add the key in ma array.

if(arr.hasOwnProperty("key1")){
      arr.unshift({key:"key1", value:"z"});
}
like image 449
John Cooper Avatar asked Feb 07 '12 13:02

John Cooper


People also ask

How do you check if a key exist in an object?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

How do you check if an element exists in an array?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if all object keys has value?

Use array.Object. values(obj) make an array with the values of each key. Save this answer.


1 Answers

To make it easier you should store your data thusly:

var map = {
       "key1": "z",
       "key2": "u"
};

Then you can do your check and if your keys don't conflict with any existing properties on the object and you don't need null values you can make it easier.

if (!map["key1"]) {
   map["key1"] = "z";
}

If you really need the full object (yours is after all just an example), I would store the object as the value of the key, not just store the objects in the array. That is, make it a map, not an array.

like image 101
tvanfosson Avatar answered Oct 05 '22 03:10

tvanfosson