[英]Comparing array value with object
非常感謝您的幫助。 我對javascript很陌生,無法弄清楚如何解決我遇到的這個問題。 基本上我有2個數組。 一個包含一個具有ID值和相應組值的對象。 第二個數組僅包含id。 我想比較兩個數組的ID,如果它們匹配,我想提取相應的組值。
例如
a = [1,2,3,4,5];
b = [{{1:group1},{2:group2},{3:group3}];
如果id與b中的id相匹配,則打印出id的組值
var a = [];
var b = [];
var c = {};
if (condition) {
c = {id:group}
b.push(c)
}
if (condition) {
a.push(id)
}
for (var i = 0; i < a.length; i++) {
//If id value in a exists in b, get id's corresponding group value from b
}
function find() {
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
if (b[j].hasOwnProperty(a[i])) {
return b[j][a[i]];
}
}
}
}
替代解決方案:
<script>
a = [
1, // index 0
2, // index 1
3, // index 2
4, // index 3
5 // index 4
];
b = [
{1:'group1'}, // index [0][1]
{2:'group2'}, // index [1][2]
{3:'group3'} // index [2][3]
];
// If id in a matches id in b then print out the id's group value
var i = 1;
for (var key in b) {
var bKeys = Object.keys(b[key]);
if(bKeys[0] == a[key]) {
console.log(b[key][i]);
}
i++;
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.