admin管理员组文章数量:1391955
Is it somehow possible to iterate an array in JS using Array.map()
and modify the index values of the resulting array?
// 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"},
];
*/
Is it somehow possible to iterate an array in JS using Array.map()
and modify the index values of the resulting array?
// 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"},
];
*/
Share
Improve this question
edited Aug 24, 2016 at 18:29
Philipp
asked Aug 16, 2016 at 19:16
PhilippPhilipp
11.4k9 gold badges69 silver badges74 bronze badges
0
2 Answers
Reset to default 3No. Array#map
performs a 1:1 mapping (so to speak).
You'd have to create a new array and explicitly assign the elements to the specific indexes:
var arrResult = [];
arrSource.forEach(function(value) {
arrResult[value.id] = value;
});
Of course you can use .reduce
for that too.
Of course you can do it as follows;
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)
Yes... always the source array gets mutated if you need some irregularities with Array.prototype.map()
such as
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));
which is not surprising.
本文标签: javascriptChange array index with arraymap()Stack Overflow
版权声明:本文标题:javascript - Change array index with array.map() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744723242a2621821.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论