[英]Change array index with array.map()
是否有可能使用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
。
当然,您可以按照以下步骤进行操作;
var arrSource = [ {id:7, name:"item 1"}, {id:10, name:"item 2"}, {id:19, name:"item 3"}, ]; newArr = arrSource.map((e,i,a) => a[a.length-1-i]); console.log(newArr)
是的...如果您需要使用Array.prototype.map()
一些异常处理,则始终会更改源数组,例如
var arrSource = [ {id:7, name:"item 1"}, {id:10, name:"item 2"}, {id:19, name:"item 3"}, ]; newArr = arrSource.map((e,i,a) => a[a.length] = e); console.log(JSON.stringify(arrSource,null,4));
这并不奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.