4

I use a library that calls an API which returns an array of objects:

new Promise((resolve) => {
  Kit.getSamples(walkingSample, (err, results) => {
    if (err) {
      return resolve([])
    }
    this.setState({
      ActivityItem: results
    })
  })
})

where ActivityItem is a an empty array defined in state. Now, this will return something like:

[{
    "end": "2020-04-25T21:45:00.000+0200",
    "quantity": 11,
    "sourceName": "Health",
    "start": "2020-04-25T21:45:00.000+0200",
    "tracked": false
  },
  {
    "end": "2020-04-25T21:41:00.000+0200",
    "quantity": 21,
    "sourceName": "Health",
    "start": "2020-04-25T21:41:00.000+0200",
    "tracked": false
  }
]

This is what an API returns, and this is what is stored inside my ActivityItem array. But apart from what API returns, I need to add one more property like 'name' to distinguish different future calls. I wonder if there is any way to add some property to that array so that it will look like this:

[{
    "name": 'Walking',
    end ": "
    2020 - 04 - 25 T21: 45: 00.000 + 0200 ", "
    quantity ": 11, "
    sourceName ": "
    Health ", "
    start ": "
    2020 - 04 - 25 T21: 45: 00.000 + 0200 ", "
    tracked ": false}, {
      "name": 'SomeOther',
      "end": "2020-04-25T21:41:00.000+0200",
      "quantity": 21,
      "sourceName": "Health",
      "start": "2020-04-25T21:41:00.000+0200",
      "tracked": false
    }]

1 Answer 1

8

You can use map to generate a new array and add a property to each object:

const newData = data.map(item => return { ...item, name: 'Walking });
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.