2

Having a problem overriding the index of array in redux state :/

I am receiving a data from an endpoint and the results are:

e.g.

data: 
 [{
    0: {id: 123, name: test1 },
    1: {id: 456, name: test2 },
    3: {id: 789, name: test3 },
 }]

But I want to change the index of the array based on the result object.

data:
 [{
    123: {id: 123, name: test1 },
    456: {id: 456, name: test2 },
    789: {id: 789, name: test3 },
 }]

Then save these to reducer.

This is the exact data that returned from an endpoint. enter image description here

I have tried

let data = action.payload.data.map(item => {
    return {
        [item.id]: item
    }
})

and got the result of

[
0: {123: {id: 123, name: 'test1'}},
1: {456: {id: 456, name: 'test2'}}
]

Any help is much appreciated!

sinnede
  • 83
  • 7

2 Answers2

1

A combination of Array.map(), Object.values() and Array.reduce() must do the trick:

const data = [{

0: {id: 123, name: "test1" },

1: {id: 456, name: "test2" },

3: {id: 789, name: "test3" },

}];

const output = data.map(obj => Object.values(obj).reduce((acc, a) => ({ ...acc, [a.id]: a }), {}));

console.log(output);
Fraction
  • 11,668
  • 5
  • 28
  • 48
0

You can use map and Object.entries and Object.fromEntries

let data = [{0: { id: 123,name: 'test1'},1: {id: 456,name: 'test2'}, 3: {id: 789,name: 'test3'},}]

let op = data.map(val => Object.fromEntries(Object.entries(val).map(([key, value]) => [value.id, value])))

console.log(op)

Or you can use map and Object.values and reduce

let data = [{0: { id: 123,name: 'test1'},1: {id: 456,name: 'test2'}, 3: {id: 789,name: 'test3'},}]

let op = data.map(val=> {
  let values = Object.values(val)
  let obj = values.reduce((op, inp) => {
    op[inp.id] = inp
    return op
  },{})
  return obj  
})

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Thanks man, but seems not working, BTW the ID is a string and this is the data returned: data = [ {fixtureId: 123,name: 'test1'}, {fixtureId: 456,name: 'test2'}, {fixtureId: 789,name: 'test3'} ] – sinnede Jun 01 '19 at 19:01
  • @siney71 what is not working can you explain the problem you're facing ? the answer is in accordance to the data you posted in question, since here key is changed so you need to used `fixtureId` instead of `id`, you can update question with the code you've tried – Code Maniac Jun 01 '19 at 19:03