1

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

3
  • 3
    Is it an array? Are you sure? Commented Mar 21, 2017 at 15:57
  • 3
    Arrays don't have keys, they have indices that should begin with 0 and not have holes. What do you really want, what is your actual problem? Commented Mar 21, 2017 at 15:58
  • It's impossible. see here Commented Mar 21, 2017 at 16:02

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.