下面是鍵/值對陣列。我想匹配下面陣列中的鍵并帶來它的值。但我的字串是“[email protected]”并遍歷下面的陣列并帶來它的值。
[{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}]
我想訪問陣列并帶來價值。
uj5u.com熱心網友回復:
我們遍歷給定的陣列,然后第二個 for 回圈只是獲取每個元素的鍵。但是如果每個物件只包含一個密鑰對,那么第二個 for 回圈將始終只運行一次。使得整體時間復雜度為 O(N)。
let a = [{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}]
let s = "[email protected]"
for(let i = 0; i<a.length; i ){
for (var key in a[i]) {
if (key === s){
console.log(a[i][key])
}
}
}
uj5u.com熱心網友回復:
let json = '[{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}]'
let o = JSON.parse(json) // Create an object from the JSON
o.forEach(function(obj) { // Loop through each object
for (const key in obj) { // Loop through the keys in the object you are up to
if (key == '[email protected]') { // If it's the key you want...
console.log(obj[key]) // ...get the value
}
}
})
另請參閱https://stackoverflow.com/a/8430501/378779
uj5u.com熱心網友回復:
我們可以遍歷陣列并檢查所需的鍵是否存在于任何鍵:值對中。
let data = [{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}];
let res = '';
for ( const item of data ) {
if ( '[email protected]' in item ) {
res = item['[email protected]'];
break;
}
}
console.log(res);
uj5u.com熱心網友回復:
嘗試這個
var arr = [{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}];
const searchKey = "[email protected]";
var res = null;
for (item of arr) {
if (searchKey in item ) {
res = item[searchKey];
break;
}
}
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/518536.html
上一篇:Json將鍵更改為值
