Search code examples
angular14

How to get the correct value in key-value pair inside an object, inside an array?


I have an array of object like this one:

[
 studentData: [
  { id: 1, name: "John Doe", yearEnrolled: "6th Grade"},
  { id: 2, name: "Jane Doe", yearEnrolled: "8th Grade"}
 ],
 teacherData: [
  { id: 1, name: "John Doe", subject: "Math"},
  { id: 2, name: "Jane Doe", subject: "English"}
 ]
]

I have a variable assignment that checks if yearEnrolled exists then gets this like this:

 let johnYearEnrolled = studentData[0]?.yearEnrolled ? studentData[0]?.yearEnrolled : "";

I'm getting johnYearEnrolled as "8th". I've also console.log this part:

studentData[0]?.yearEnrolled

and I'm getting this

({ id: 1, name: "John Doe", yearEnrolled: "6th Grade"})

What I am doing wrong? I should be getting the "6th grade" as a result and not "8th grade".

Actually, I don't need John's actual year enrolled. I wanted the first person's year enrolled in the array. This data is from the back-end and it changes.


Solution

  • The reason you are seeing this is because a javascript object does not preserve order.

    "In JavaScript, object properties are not guaranteed to be in any particular order. The order in which the properties are defined in the object literal or added to the object can be different from the order in which they are accessed." https://saturncloud.io/blog/does-javascript-guarantee-object-property-order/#:~:text=In%20JavaScript%2C%20object%20properties%20are,in%20which%20they%20are%20accessed.

    So basically in your case, the javascript object order is being 'scrambled' so using index 0 does not guarantee that you'll get that entry corresponding to 6th grade.

    One way you can try fixing this is to use [] instead of {} to create a javascript list & then reference it via index because a javascript list does indeed keep the order.

    More than likely, when you print it, it just so happens to use the order you are expecting - but that is not guaranteed.