2016-11-05 70 views
2

我想檢查下面的JSON對象中的某個鍵是否包含某個值。假設我想檢查任何對象中的鍵「name」是否具有值「Blofeld」(這是正確的)。我怎樣才能做到這一點?使用Javascript檢查JSON對象是否包含值

[ { 
    "id" : 19, 
    "cost" : 400, 
    "name" : "Arkansas", 
    "height" : 198, 
    "weight" : 35 
}, { 
    "id" : 21, 
    "cost" : 250, 
    "name" : "Blofeld", 
    "height" : 216, 
    "weight" : 54 
}, { 
    "id" : 38, 
    "cost" : 450, 
    "name" : "Gollum", 
    "height" : 147, 
    "weight" : 22 
} ] 
+1

[有沒有這樣的事情作爲一個 「JSON對象」(http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json /) – adeneo

+0

'obj.name ===「Blofeld」' – vlaz

+1

['Array.prototype.some()'](https://developer.mozilla .org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some) – Andreas

回答

6

你也可以使用Array.some()功能:

var arr = [ { 
 
    "id" : 19, 
 
    "cost" : 400, 
 
    "name" : "Arkansas", 
 
    "height" : 198, 
 
    "weight" : 35 
 
}, { 
 
    "id" : 21, 
 
    "cost" : 250, 
 
    "name" : "Blofeld", 
 
    "height" : 216, 
 
    "weight" : 54 
 
}, { 
 
    "id" : 38, 
 
    "cost" : 450, 
 
    "name" : "Gollum", 
 
    "height" : 147, 
 
    "weight" : 22 
 
} ]; 
 

 
console.log(arr.some(item => item.name === 'Blofeld')); 
 
console.log(arr.some(item => item.name === 'Blofeld2'));

+0

非常感謝!這是我付出的解決方案,它的工作非常出色! –

0

隨着通過陣列中的所有對象的簡單循環,使用hasOwnProperty()

var json = [...]; 
var wantedKey = ''; // your key here 
var wantedVal = ''; // your value here 

for(var i = 0; i < json.length; i++){ 

    if(json[i].hasOwnProperty(wantedKey) && json[i][wantedKey] === wantedVal) { 
    // it happened. 
    break; 
    } 

} 
+0

當然,k ey不見了。我剛剛修改了它,謝謝! – wscourge

0

這會給你與姓名匹配的元素的數組=== 「Blofeld」:

var data = [ { 
 
    "id" : 19, 
 
    "cost" : 400, 
 
    "name" : "Arkansas", 
 
    "height" : 198, 
 
    "weight" : 35 
 
}, { 
 
    "id" : 21, 
 
    "cost" : 250, 
 
    "name" : "Blofeld", 
 
    "height" : 216, 
 
    "weight" : 54 
 
}, { 
 
    "id" : 38, 
 
    "cost" : 450, 
 
    "name" : "Gollum", 
 
    "height" : 147, 
 
    "weight" : 22 
 
} ]; 
 

 
var result = data.filter(x => x.name === "Blofeld"); 
 
console.log(result);

+0

感謝您回答我的問題!我去了@ Andriy的解決方案,所以我沒有嘗試這個。 –

1

寫一個sim ple函數來檢查對象數組是否包含特定值。

var arr=[{ 
    "name" : "Blofeld", 
    "weight" : 54 
},{ 
    "name" : "", 
    "weight" : 22 
}]; 

function contains(arr, key, val) { 
    for (var i = 0; i < arr.length; i++) { 
     if(arr[i][key] === val) return true; 
    } 
    return false; 
} 

console.log(contains(arr, "name", "Blofeld")); //true 
console.log(contains(arr, "weight", 22));//true 

console.log(contains(arr, "weight", "22"));//false (or true if you change === to ==) 
console.log(contains(arr, "name", "Me")); //false 
+0

感謝您回答我的問題!我沒有嘗試過,因爲@ Andriy的解決方案更簡單/更短。 –

+0

我同意Andriy有一個更簡單的解決方案。我認爲這是經驗上的差距。 –