我在处理一个应该从另一个对象数组返回一个对象数组的函数时卡住了。如下所示,我只使用一个键并返回一个“简单”数组而不是对象数组:
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);Run Code Online (Sandbox Code Playgroud)
如果我使用 2 个(或更多)键,我仍然会得到一个与最后使用的键相对应的“简单”值数组:
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);Run Code Online (Sandbox Code Playgroud)
我想要的是:
var myArr = [
{name: "United Kingdom", code: "GB"},
{name: "Romania", code: "RO"}
]
Run Code Online (Sandbox Code Playgroud)
有什么不见了?
function pluck(array, key1, key2) {
return array.map(x => ({
[key1]: x[key1],
[key2]: x[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);Run Code Online (Sandbox Code Playgroud)
好像你打算做那样的事情。您可以通过第二个参数是一个键数组,并在 map 函数内部迭代每个键并将其逐个添加到对象中来使其更通用。