2017-06-08 120 views
0

对于任何帮助我都会很感激。我很新的JavaScript和不能找出如何解决这个问题,我有。基本上我有2个数组。一个包含一个具有id值和相应组值的对象。第二个数组只包含id。我想比较两个数组的ID,如果它们匹配,我想提取相应的组值。将数组值与对象进行比较

E.g.

a = [1,2,3,4,5];

b = [{1:group1},{2:group2},{3:group3}];

如果ID在B A比赛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 
} 
+1

苯并[a [i]]应该努力!如果它没有定义,a [i]不在b中。 –

回答

1
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]]; 
     } 
     } 
    } 
} 
1

另一种解决方案:

<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> 
相关问题