Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - check if key exists - if not create it, all in one line

Tags:

javascript

I'm looking for a one-liner way of checking if a key exists and if it doesn't create it.

var myObject = {};  //Anyway to do the following in a simpler fashion?  if (!('myKey' in myObject)) {     myObject['myKey'] = {}; } 
like image 980
KingKongFrog Avatar asked Jun 26 '16 00:06

KingKongFrog


People also ask

How do you check if a key exists in a JavaScript array?

Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.

How do you check if a key is present in an object in JS?

Use the in operator to check if a key exists in an object, e.g. "key" in myObject . The in operator will return true if the key is present in the object, otherwise false is returned. Copied! The syntax used with the in operator is: string in object .

How do you know if a key is present 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 key is exist or not?

Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.


1 Answers

Short circuit evaluation:

!('myKey' in myObject) && (myObject.myKey = {}) 
like image 185
undefined Avatar answered Sep 27 '22 23:09

undefined