2

I am getting a response from my API and I'm trying to rename a nested object property for an array of objects in my action before I sent it to the reducer. Here is generally what the response looks like:

[
  {
    attributes: {
      name: "Item 1",
      price_cents: 1500
    }
  },
  {
    attributes: {
      name: "Item 2",
      price_cents: 1000
    }
  },
  ...
]

and I would like to change price_cents to price. How could I change this before I use it as the payload to the reducer?

suman j
  • 6,710
  • 11
  • 58
  • 109
AHinson
  • 661
  • 2
  • 7
  • 15

2 Answers2

3

You can use Array#map to walk over each of the values in the response array, and create a new object with the properties and names you want:

const actionCreator = (response) => ({
  type: 'ACTION_TYPE',
  payload: response.map((item) => ({
    attributes: {
      name: item.attributes.name,
      price: item.attributes.price_cents
    }
  })
});
jevakallio
  • 35,324
  • 3
  • 105
  • 112
1

Write a filter to change attribute value, when the response succesfully returns, filter the response and reduce it.

JSON property name change : Rename the property names and change the values of multiple objects

JSON property name change (2) : change property name

Community
  • 1
  • 1
Tugrul
  • 1,760
  • 4
  • 24
  • 39