[英]Checking if a key exists in a JS object
我有以下 JavaScript object:
var obj = {
"key1" : val,
"key2" : val,
"key3" : val
}
有沒有辦法檢查數組中是否存在一個鍵,類似於這個?
testArray = jQuery.inArray("key1", obj);
不起作用。
我必須像這樣遍歷 obj 嗎?
jQuery.each(obj, function(key,val)){}
那不是一個 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
map.has(key)
是ECMAScript 2015最新的檢查映射中鍵是否存在的方法。 有關完整的詳細信息, 請參閱此內容。
你可以試試這個:
const data = {
name : "Test",
value: 12
}
if("name" in data){
//Found
}
else {
//Not found
}
最簡單的方法是
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'); }
使用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
這對我來說就像一個魅力。 我在一個foreach
function 里面這不起作用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';
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.