105

I have the following JavaScript object:

var obj = {
    "key1" : val,
    "key2" : val,
    "key3" : val
}

Is there a way to check if a key exists in the array, similar to this?

testArray = jQuery.inArray("key1", obj);

does not work.

Do I have to iterate through the obj like this?

jQuery.each(obj, function(key,val)){}
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
user2065483
  • 1,195
  • 3
  • 8
  • 12
  • 4
    js - object literal :) (not jQuery object) – funerr Jun 15 '13 at 18:10
  • True ;), shows that I don't have a js background - started with the jQuery library right from the start, and I believe I need to learn the basics... – user2065483 Jun 15 '13 at 18:30
  • `obj.has("key1")` will work if you are using ES6. – Diablo May 30 '17 at 09:03
  • 2
    Possible duplicate of [Checking if a key exists in a JavaScript object?](https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object) – Gerhard Powell Sep 15 '17 at 21:56
  • 2
    @Diablo I think you're trying to say `obj.hasOwnProperty("key1")` instead of just `has`? – Aminu Kano Aug 21 '18 at 09:11
  • @AminuKano Yes, you're right. I meant `obj.hasOwnProperty("key1")` . I simply overlooked my comment before pasting it here! – Diablo Oct 23 '21 at 19:48

9 Answers9

203

Use the in operator:

testArray = 'key1' in obj;

Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.

Sirko
  • 72,589
  • 19
  • 149
  • 183
60

That's not a jQuery object, it's just an object.

You can use the hasOwnProperty method to check for a key:

if (obj.hasOwnProperty("key1")) {
  ...
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • you should not use it. it is said to be slow . best way is to use 'key' in object – hannad rehman Oct 03 '17 at 07:23
  • @hannadrehman Can you give me a reference to the doc/article where it is mentioned? :) – Nabin Nov 08 '17 at 04:51
  • 1
    @Fan_of_Martijn_Pieters i follow strict ESlint rule set. it is mentioned there as one of the rules.https://eslint.org/docs/rules/no-prototype-builtins – hannad rehman Nov 08 '17 at 06:37
  • @hannadrehman Don't use the key-in-object, it can be plain wrong, this is the best way. –  Oct 09 '19 at 06:53
  • Downvoted because this does not work when detecting keys with a null value. For example, if the value of obj["key1"] == null (so key1 exists in obj and its value is null), this will return a false result that key1 is not in obj. – user1258361 May 15 '20 at 20:32
  • @user1258361: You are mistaken. If the key exists in the object the `hasOwnProperty` method will return `true` even if the value of the property is null. – Guffa Oct 15 '21 at 18:25
9
var obj = {
    "key1" : "k1",
    "key2" : "k2",
    "key3" : "k3"
};

if ("key1" in obj)
    console.log("has key1 in obj");

=========================================================================

To access a child key of another key

var obj = {
    "key1": "k1",
    "key2": "k2",
    "key3": "k3",
    "key4": {
        "keyF": "kf"
    }
};

if ("keyF" in obj.key4)
    console.log("has keyF in obj");
Fernando_Jr
  • 430
  • 5
  • 10
5

Above answers are good. But this is good too and useful.

!obj['your_key']  // if 'your_key' not in obj the result --> true

It's good for short style of code special in if statements:

if (!obj['your_key']){
    // if 'your_key' not exist in obj
    console.log('key not in obj');
} else {
    // if 'your_key' exist in obj
    console.log('key exist in obj');
}

Note: If your key be equal to null or "" your "if" statement will be wrong.

obj = {'a': '', 'b': null, 'd': 'value'}
!obj['a']    // result ---> true
!obj['b']    // result ---> true
!obj['c']    // result ---> true
!obj['d']    // result ---> false

So, best way for checking if a key exists in a obj is:'a' in obj

Ali Hallaji
  • 3,712
  • 2
  • 29
  • 36
3

use the hasOwnProperty(),

if (!obj.hasOwnProperty(key)) {

}

For Example :

const object1 = {
        one : 'value of one',
        two : 'value of two',
        three : 'value of three',
    };

console.log(object1.hasOwnProperty('one'));
// expected output: true

console.log(object1.hasOwnProperty('value of one'));
// expected output: false

console.log(object1.hasOwnProperty('four'));
// expected output: false
Muhammad Shafaf
  • 346
  • 2
  • 6
1

map.has(key) is the latest ECMAScript 2015 way of checking the existance of a key in a map. Refer to this for complete details.

Diablo
  • 443
  • 7
  • 21
1

You can try this:

const data = {
  name : "Test",
  value: 12
}

if("name" in data){
  //Found
}
else {
  //Not found
}
Dino
  • 7,779
  • 12
  • 46
  • 85
Achsuthan
  • 11
  • 1
0

the simplest way is

const obj = {
  a: 'value of a',
  b: 'value of b',
  c: 'value of c'
};

if(obj.a){
  console.log(obj.a);
}else{
  console.log('obj.a does not exist');
}
Khan
  • 5,052
  • 5
  • 22
  • 23
-3

This works for me like a charm. I'm inside a foreach function this didn't work obj.hasOwnProperty("key1") also this "key1" in obj

let $schedule = {lesson:'asd',age:'sad'}
    
$schedules.forEach(function(e) {
    if (e['lesson']) {
        $title = e.lesson.lesson_name;
    } else {
        $title = 'No lesson Attached';
    }
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31