Pan Chrono
Pan Chrono

Reputation: 420

Javascript map an array to a new one with defined keys

what i need is to transform this Array

[
   0: {id: 1},
   1: {id: 2}
]

to

[
   1: {id: 1},
   2: {id: 2}
]

Just switching keys I suppose, Im trying to use .map but all i can change are the values not the keys

Upvotes: 1

Views: 43

Answers (1)

Icepickle
Icepickle

Reputation: 12796

I think you can solve it easily enough with reduce

It starts with an empty array, and during each iteration 1 item is added, at the index of the items id field.

This will give you an array with a length that might not be what you have expected, so I would suggest to look a bit deeper into your requirements.

var arr = [
   {id: 1},
   {id: 2}
];

var result = arr.reduce( (container, item) => { 
  container[item.id] = item; 
  return container;
}, [] );
console.log( result[1] );
console.log( result[2] );
console.log( result );

You could always make it an object with the correct keys, with pretty much the same syntax

    var arr = [
       {id: 1},
       {id: 2}
    ];

    var result = arr.reduce( (container, item) => { 
      container[item.id] = item; 
      return container;
    }, {} );
    console.log( result[1] );
    console.log( result[2] );
    console.log( result );

And important thing to note, is that with the array, you have an undefined value at position 0, the object version doesn't have it. It would make more sense to use the object version, and not the array. As mentioned in the comments, it's not a very good idea to have gaps in your array.

Upvotes: 2

Related Questions