Mosen
Mosen

Reputation: 75

How to Manage the response of the API in react?

i did a request to the API, then the response is as the following:

data1 = [{id: 1, code:1, title:title1}, {id:2, code:3, title:title2}, ...]

Now i would like to extract an array of the titles of the above response as below:

titles = [title1, title2, ....]

how can i do it by map?

And the second question:

Consider if the response would be as follow:

data2 = [{id: 1, code:1, title:title1, chapters:[{id:1, chapter: chapter1},{id:2, chapter: chapter2}, ...]}, {id:4, code:5, title:title3, chapters:[{id:4, chapter: chapter3}, ...]}, ...]

In this case how can i extract an array of the chapters as following:

chapters = [chapter1, chapter2, chapter3]

I tried to do them as below:

for the first question:

title = data1.map((item) => {item.title})

for the second one i did:

chapters = data2.chapters.map((item) => {item.chapter})

But it doesn't work. I think some where there are error in syntaxes.

Can any one help me how to manage these data? Thank you.

Upvotes: 0

Views: 38

Answers (2)

sleepwalker
sleepwalker

Reputation: 1032

Yep, you are wrong with syntax.

Firs case - title = data1.map((item) => {item.title}) You've wrapped item.title with {}, so you should add return. Or omit {}. For example: title = data1.map(item => item.title)

Second case - same issue with {}, but you should also use flatMap because you need flat list in result. If you write with regular map - you won't get desired ["chapter1", "chapter2"].

See also detailed example below.

const data1 = [
  { id: 1, code: 1, title: "title1" },
  { id: 2, code: 3, title: "title2" }
];
const data1_mapped = data1.map(d => d.title);
console.log(data1_mapped);

const data2 = [
  {
    id: 1,
    code: 1,
    title: "title1",
    chapters: [{ id: 1, chapter: "chapter1" }, { id: 2, chapter: "chapter2" }]
  },
  {
    id: 2,
    code: 2,
    title: "title2",
    chapters: [{ id: 1, chapter: "chapter22" }, { id: 2, chapter: "chapter32" }]
  }
];
const data2_mapped = data2.flatMap(d => d.chapters.map(c => c.chapter));
console.log(data2_mapped);

Upvotes: 1

Nathan Hall
Nathan Hall

Reputation: 407

You are not returning a value. Try removing braces like so...

title = data1.map((item) => item.title)

chapters = data2.chapters.map((item) => item.chapter)

See this for more info on the issue: Meaning of curly braces in array.map()

Upvotes: 1

Related Questions