gpt4 book ai didi

javascript - 使用 array.map() 更改数组索引

转载 作者:行者123 更新时间:2023-11-28 18:26:42 25 4
gpt4 key购买 nike

是否可以使用 Array.map() 在 JS 中迭代数组并修改结果数组的索引值?

// I start with this values:
var arrSource = [
{id:7, name:"item 1"},
{id:10, name:"item 2"},
{id:19, name:"item 3"},
];

var arrResult = arrSource.map(function(obj, index) {
// What to do here?
return ???;
});

/*
This is what I want to get as result of the .map() call:

arrResult == [
7: {id:7, name:"item 1"},
10: {id:10, name:"item 2"},
19: {id:19, name:"item 3"},
];
*/

最佳答案

没有。 Array#map 执行 1:1 映射(可以这么说)。

您必须创建一个新数组并显式地将元素分配给特定索引:

var arrResult = [];
arrSource.forEach(function(value) {
arrResult[value.id] = value;
});

当然你也可以使用 .reduce 来实现。

关于javascript - 使用 array.map() 更改数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com