Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first object from array of objects in react [duplicate]

Tags:

reactjs

I am trying to get the first object from an array of objects. Fetched data in componentDidMount and return:

var array1 = [
    {
      Id: 1, 
      Categories: 200 
    },
    {
      Id: 2, 
      Categories: 100 
    }
]

(real data is much more complicated but in the same format) What I want is this:

array2 = [
    Id: 1, 
    Categories: 200
]

I was using

var iterator1 = array1.entries();
let array2 = iterator1.next().value

and when I console.log(array2) it shows the array data (all key and value is in index 1 of array), then when I console.log(array2[1].Id) it shows undefined right inside the render method in class component. I use the same code in other IDE but not using react the code work. Could someone explain to me please? Appreciate for any help.

Edit: At the end I found that I asked the wrong question. I failed to get the data because I declared the data in my reducer to object instead of array. I mark the answer by larz since you just need to put index 0 to get the first object from the array of objects.

like image 547
andromad Avatar asked Feb 03 '23 22:02

andromad


1 Answers

Grab the first item in your array using [0], which returns an object in your case. Then you can call .Id on it to get the id.

var array1 = [
    {
      Id: 1, 
      Categories: 200 
    },
    {
      Id: 2, 
      Categories: 100 
    }
];

var first = array1[0];

console.log(first, first.Id);
like image 112
larz Avatar answered May 16 '23 01:05

larz