1

I'm currently trying to convert an array into an object with the array index as the property of the created object.

Example Array: ['a','b','c']

Expected Object result: {'1':'a','2':'b','3':'c'}

My code is below, it worked when I used map method but when I use the reduce method instead it comes out weird way:

let sampleData = ['a','b','c'];
    
    let convertArrToObjWithIndexProp = (arr) => {
      /*let res = {};
      arr.map((v,k)=> {
       res[k+1]=v;
      })
      return res;*/
      //--> this outputs {'1':'a','2':'b','3':'c'}
      
      return arr.reduce((iv,cv,i)=>{
        return Object.assign(iv,iv[i+1]=cv);
      },{});
      //--> this outputs instead {'0':'c','1':'a','2':'b','3':'c'}
    }
    console.log(convertArrToObjWithIndexProp(sampleData));

Can someone explain to me why its coming out like that?

Also is using reduce better than using map?

JSmith
  • 4,519
  • 4
  • 29
  • 45
Joshua Rajandiran
  • 2,788
  • 7
  • 26
  • 53
  • `Object.assign(iv, {[i+1]: cv});` should work. I don't know what your code is currently doing but it's looking pretty weird – Axnyff Aug 25 '18 at 16:28
  • Possible duplicate of https://stackoverflow.com/questions/49469699/array-to-object-reduce If you have an Array of Objects and you need to copy each Object the correct `Object.assign` syntax would be: `return arr.reduce((iv, cv, i) => Object.assign({}, iv, {[i]: cv}), {});` – Eydrian Aug 27 '18 at 13:57

5 Answers5

3

The problem is that result of this expression: iv[i+1]=cv is cv, which you then Object.assign to the accumulator. You could make it simpler with a simple assignment:

let sampleData = ['a','b','c'];
    
let convertArrToObjWithIndexProp = (arr) => 
    arr.reduce((iv,cv,i) => (iv[i+1] = cv, iv),{});

console.log(convertArrToObjWithIndexProp(sampleData));
Mark
  • 90,562
  • 7
  • 108
  • 148
1

Don't use Object.assign. Just update your object and return it.

let sampleData = ['a','b','c'];
    
    let convertArrToObjWithIndexProp = (arr) => {       
      return arr.reduce((iv,cv,i)=>{
         iv[i+1]=cv
         return iv
      },{});
    }
    console.log(convertArrToObjWithIndexProp(sampleData));
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
0

You can achieve it by doing this

let array = ['a','b','c'];
return array.reduce((acc, currentValue, index) => {
    const key= index + 1;
    acc[key] = currentValue;
    return acc;
}, {});

Output will be like this

{
  "1": "a",
  "2": "b",
  "3": "c"
}
Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
0

var arr = ['a','b','c'];
var result = arr.reduce((obj, val, index) => {
  obj[index + 1] = val;
  return obj; 
}, {});

console.log(result);
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
0

I'd do it with Array.reduce function, and Object computed property.

var sampleData = ['a', 'b', 'c'];
console.log(sampleData.reduce((mem, curr, index) => ({ ...mem,
  [index + 1]: curr
}), {}))
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317