10

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.

8
  • 7
    Arrays start at 0. Try array2[0].id Commented Aug 23, 2018 at 16:20
  • 1
    this will give undefined, even in other IDE, because all keys and values is in index 1, index 0 show 0 in console.log Commented Aug 23, 2018 at 16:25
  • What are you talking about/ Commented Aug 23, 2018 at 16:26
  • No. array2 holds [0, {Id:1, Categories: 200}]. Thus, OP is doing right. Commented Aug 23, 2018 at 16:27
  • 1
    @andromad can you explain why you aren't using the much simpler: array1[0] to get the first element of array1. Commented Aug 23, 2018 at 16:32

1 Answer 1

15

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);

Sign up to request clarification or add additional context in comments.

10 Comments

In Javascript, the first item in an array is always 0, not 1. It can be useful for certain things, but it can also be slightly annoying when you first start using the language if you're not used to it (I came from Lua.)
No. array2 holds [0, {Id:1, Categories: 200}]. Thus, OP is doing right.
@BhojendraRauniyar Well I didn't mention anything about array2 so I'm not sure why you commented.
Try OP code, then you'll understand.
@BhojendraRauniyar Then comment on OP's code, not mine. There is no array2 in mine because that's an unnecessary step.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.