Reputation: 363
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
}]
Upvotes: 4
Views: 3276
Reputation: 3274
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 });
Upvotes: 8