Home > Mobile >  How to save nested data fom API response into a variable
How to save nested data fom API response into a variable

Time:11-05

I have an API response

const response = [

{ id:1, tags:[data:"save1"] },

{ id:2, tags:[data:"save2"] },

{ id:3, tags:[data:"save3"] },

]

I want to save the data of all tags into a single array like below e.g

const newArr = [{save1},{save2},{save3}]

how can i achieve that

I am new to in this any help will be appreciated. thank you

CodePudding user response:

The response object you posted in the question doesn't seem to be in a valid format.

Assuming the below is the one you were trying to post,

const response = [

{ id:1, tags:[{data:"save1"}] },

{ id:2, tags:[{data:"save2"}] },

{ id:3, tags:[{data:"save3"}] }

]

You can iterate the object with a map function and then push the tags in an array like this:

const tagsArray = [];
response.map((res) => {
  tagsArray.push(res.tags[0].data);
})

If you print the tagsArray, the final result may look something like this:

["save1", "save2", "save3"]

CodePudding user response:

if you need the id/key

 const response = [

          { "id": 1, "tags": [ { "data":"save1" } ] },
          { "id": 2, "tags": [  ] },
          ]

          const transformed = response
          ?.map(item => ({id: item.id, data: item?.tags?.[0]?.data }))
          ?.filter(item => !!item.data)
  • Related