How to map data returned from an API call

Hello,

I am trying to map the data that is being returned from an api call and in order to extract a lot of data at the same time with one call, the api returns nested data i.e. see the below example data being returned.

[
{“id”:1, “created_at”:1611595283381, “title”:“Some title A”, “desc”:“Some desc A”, “_comments”:[{“id”:1,“created_at”:1611596409958,“comment”:“comment ABC”, “_user_comment”:{“id”:3,“name”:“Bari”,“picture”:{“url”:“https://xyz/Picture1.jpg”}}}],

{“id”:2, “created_at”:1611595283391, “title”:“Some title B”, “desc”:“Some desc B”, “_comments”:[{“id”:2,“created_at”:1611596409958,“comment”:“comment XYZ”, “_user_comment”:{“id”:5,“name”:“Andy”,“picture”:{“url”:“https://xyz/Picture2.jpg”}}}]
]

In order to map the data being returned into easier to work with names, I am trying to map the data. See an example below of the mapping of data I do.

Mapping:

{{data}}.map(item => ({
“id”: item.id,
“createDt”: item.created_at,
“title”: item.title,
“desc”: item.desc,
“comments”: item._comments
}))

{{data.comments}}.map(item => ({
“id”: item.id,
“createDt”: item.created_at,
“comment”: item.comment,
“user”: item._user_comment
}))

{{data.comments.user}}.map(item => ({
“id”: item.id,
“name”: item.name,
“picture”: item.picture
}))

return {{data}}

Once I do a second map, I get the below shown error. If I comment out the 2nd and 3rd mapping of data, I no longer get the error.

Error I am getting:
Screenshot - Sample Data 19

Is it possible to map the 1st level of data and then map additional levels of data that are objects themselves? Or is this not possible?

Thanks.

hi @ObyY, looks like the array that you received is not valid. I can recommend MDN for great docs.
Try to use this code snippet:

const allData = {{data}};
function mapComments(comments) {
return comments.map(item => ({
id: item.id,
createDt: item.created_at,
comment: item.comment,
user: mapUser(item._user_comment)
}));
}
function mapUser(user) {
return {
id: item.id,
name: item.name,
picture: item.picture
};
}
const mappedData = allData.map(item => ({
id: item.id,
createDt: item.created_at,
title: item.title,
desc: item.desc,
comments: mapComments(item._comments)
}));
return mappedData;

I hope you find this information useful.

Thanks. I will try this and see if this works for me.

I have tried this now and it worked. Thanks!

Glad to hear that, @ObyY!