programing

JS 개체에 키가 있는지 확인

css3 2023. 10. 17. 20:27

JS 개체에 키가 있는지 확인

다음과 같은 자바스크립트 객체가 있습니다.

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

이것과 비슷한 키가 배열에 존재하는지 확인할 수 있는 방법이 있습니까?

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

작동하지 않습니다.

이렇게 obj를 반복해야 하나요?

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

연산자 사용:

testArray = 'key1' in obj;

사이드노트:거기서 얻은 것은 사실 jQuery 객체가 아니라 단순한 자바스크립트 객체일 뿐입니다.

그것은 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

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

사용.hasOwnProperty(),

if (!obj.hasOwnProperty(key)) {

}

예:

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

다음을 시도해 볼 수 있습니다.

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

이것은 저에게 매력적으로 느껴집니다.저는 안에 있습니다.foreach기능 이것은 작동하지 않았습니다.obj.hasOwnProperty("key1")이것도"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';
    }
});

언급URL : https://stackoverflow.com/questions/17126481/checking-if-a-key-exists-in-a-js-object