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);
As pointed out in the comments, your b
& c
are not valid JavaScript
arrays. If you need key value pairs, you need to use an Object
- which uses curly braces {}
to enclose the key:value
pairs.
Assuming
// 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',
}
You can try
// 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];
}