I got stuck while working on a function that should return an array of objects from another array of objects. As can be seen below, I use only one key and return a "simple" array instead of an array of objects:
function pluck(array, key) {
return array.map(x => x[key]);
}
var myArr = [{
name: "United Kingdom",
alpha3: "GBR",
code: "GB",
region: "Europe",
tax: 5,
status: 1
}, {
name: "Romania",
alpha3: "ROM",
code: "RO",
region: "Europe",
tax: 3,
status: 1
}];
myArr = pluck(myArr, 'name');
console.log(myArr);
If I use 2 (or more) keys, I still get a "simple" array of values corresponding to the last key used:
function pluck(array, key1, key2) {
return array.map(x => x[key1, key2]);
}
var myArr = [{
name: "United Kingdom",
alpha3: "GBR",
code: "GB",
region: "Europe",
tax: 5,
status: 1
}, {
name: "Romania",
alpha3: "ROM",
code: "RO",
region: "Europe",
tax: 3,
status: 1
}];
myArr = pluck(myArr, 'name', 'code');
console.log(myArr);
What I want is:
var myArr = [
{name: "United Kingdom", code: "GB"},
{name: "Romania", code: "RO"}
]
What is missing?