JS 객체에 키가 있는지 확인 “key2”

다음 JavaScript 개체가 있습니다.

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

이와 비슷한 배열에 키가 있는지 확인하는 방법이 있습니까?

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

작동하지 않습니다.

이렇게 obj를 반복해야합니까?

jQuery.each(obj, function(key,val)){}


답변

in연산자 사용 :

testArray = 'key1' in obj;

사이드 노트 : 당신이 얻은 것은 실제로 jQuery 객체가 아니라 평범한 JavaScript 객체입니다.


답변

그것은 jQuery 객체가 아니라 객체 일뿐입니다.

hasOwnProperty 메서드를 사용하여 키를 확인할 수 있습니다.

if (obj.hasOwnProperty("key1")) {
  ...
}

답변

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

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

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

다른 키의 하위 키에 액세스하려면

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

if ("keyF" in obj.key4)
    console.log("has keyF in obj");

답변

위의 답변은 좋습니다. 그러나 이것도 좋고 유용합니다.

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

if 문에서 특별한 짧은 스타일의 코드에 적합합니다.

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');
}

참고 : 키가 null 또는 “”이면 “if”문이 잘못된 것입니다.

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

따라서 obj에 키가 있는지 확인하는 가장 좋은 방법은 다음과 같습니다.'a' in obj


답변

이것을 시도 할 수 있습니다.

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

if("name" in data){
  //Found
}
else {
  //Not found
}

답변

map.has(key)
지도에서 키의 존재를 확인 하는 최신 ECMAScript 2015 방법입니다. 자세한 내용은 이것을 참조 하십시오.


답변

가장 간단한 방법은

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');
}