如何在JavaScript中从另一个数组值中查找数组键?

时间:2018-02-01 13:29:27

标签: javascript

我确实在Stack Overflow上搜索,但我仍感到困惑。

有两个JavaScript数组: a b

var a = ['US','UK'];
var b = [
    US: 'United States',
    UK: 'United Kingdom',
    CN: 'China',
    JP: 'Japan'
];

如何获得美国'和'英国' by' US'和' UK',然后创建一个新的数组 c ,如下所示?

var c = [
    US: 'United States',
    UK: 'United Kingdom'
]

3 个答案:

答案 0 :(得分:1)

var a = ['US','UK'];
var b = {
         'US': 'United States',
         'UK': 'United Kingdom',
         'CN': 'China',
         'JP': 'Japan'
         };

one = {};
for (var key of a){
   one[key] = b[key];
}
console.log(one);


two = {};
for (let i = 0; i < a.length; i++){
    two[a[i]] = b[a[i]];
}
console.log(two);

three = {};
a.forEach(function(el){
    three[el] = b[el];
});
console.log(three);

正如评论中所指出的,您的b&amp; c不是有效的JavaScript数组。如果您需要键值对,则需要使用Object - 使用花括号{}来封闭key:value对。

<强>假设

// b holds the master list of key-value pairs 
// from b, you will fetch the pairs with keys present in a`

Input:-

var a = ['US','UK'];
var b = {
         'US': 'United States',
         'UK': 'United Kingdom',
         'CN': 'China',
         'JP': 'Japan'};

and required:-
c = {    'US': 'United States',
         'UK': 'United Kingdom',
}

你可以尝试

// Traditional approach using a normal for loop
c = {};
for (let i = 0; i < a.length; i++){
    c[a[i]] = b[a[i]];
}

// Slightly modern forEach approach
c = {};
a.forEach(function(el){
    c[el] = b[el];
});

// Modern approach using for...of loop
c = {};
for (let key of a){  
   c[key] = b[key];
}

答案 1 :(得分:1)

输入

var a = ['US', 'UK'];

//b must be object
var b = {
     'US': 'United States',
     'UK': 'United Kingdom',
     'CN': 'China',
     'JP': 'Japan'
};

结果

var c = {};

for (var i=0; i < a.length; i++)
{
    c[ a[i] ] = b[ a[i] ];
}

甚至更简单

var c = {};

for (var i of a)
{
    c[ i ] = b[ i ];
}

答案 2 :(得分:-1)

Another way using underscoreJS(-.each) //\\ http://underscorejs.org/
====================================================================
var a = ['US','UK'];
var b = [{
         'US': 'United States',
         'UK': 'United Kingdom',
         'CN': 'China',
         'JP': 'Japan'
}];
var count = 0;
var c = {};
_.each(b[0], function(v,k){
    if(a[count] == k){
        c[a[count]] = v;
    }
    count++;
});
console.log(c);