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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With