Arunya
Arunya

Reputation: 291

How to console id from JSON objects using reactjs

My objective is to get the id's from JSON array like {id: 123456}. but i couldn't able to get in this way.

here is a some JSON data:

 var categoryArray = [
      {id: '1', name: 'Category_1'},
      {id: '2', name: 'Category_2'},
      {id: '3', name: 'Category_3'},
      {id: '4', name: 'Category_4'}
     ];

when i console res.data then it is showing {id: ......} but when i do res.data.id it is showing as undefined. Can anyone help me in this?

Upvotes: 0

Views: 42

Answers (2)

Thanveer Shah
Thanveer Shah

Reputation: 3333

You can just iterate over the array.

Example:

categoryArray.forEach(val => console.log(val.id));

Upvotes: 0

CevaComic
CevaComic

Reputation: 2114

In your case you have multiple ids, so you have to iterate through the array and you can print all ids. You can use map do achieve that:

res.data.map(el => console.log(el.id));

To get all the ids as you want:

const allIds = res.data.map(el => { return {id: el.id} })

Upvotes: 1

Related Questions