Access the First Element of JSON Object Array

Have you ever been given a task to get or access the first element of a JavaScript Object Array? How can you get what you needed in a JavaScript object?

As we all know, there's no numbered index included in the JavaScript object, what should we do if we need to get the first element of a JavaScript Object Array? Fear not, in javascript, it is an easy task to deal with JSON objects array. And we will provide methods for this issue in the following sections.

How to Access the First Element of JSON Object Array

Method 1

If you are given a JavaScript object and required to access the first element of it, please see the details below.

1. You should firstly take the JavaScript Object in a variable;

2. And then use the object.keys(objectName) method to get all the keys of the JavaScript object;

3. Finally, use indexing to get the first element.

<script> 
   var up1 = document.getElementById('example_UP1'); 
   var up2 = document.getElementById('example_UP2'); 
   var down = document.getElementById('example_DOWN');
          
   var obj = { 
      "Prop_1": ["Val_11", "Val_12", "Val_13"], 
      "Prop_2": ["Val_21", "Val_22", "Val_23"], 
      "Prop_3": ["Val_31", "Val_32", "Val_33"]
     };
          
   up1.innerHTML = "Click to get the "+"first element of Object.";
   up2.innerHTML = JSON.stringify(obj); 
          
   function example_Fun() {
      down.innerHTML = "The first element = '" + 
      Object.keys(obj)[0] + "'
      Value = '"
      + obj[Object.keys(obj)[0]] + "'";
     } 
</script>

Method 2

The following method will work on any JavaScript-based framework. Firstly, let's take a dataset as an example.

const dataset = {
  "valuations": [
    [
      {
        "Price": 385000,
        "PriceRange": {
          "lower": 336000,
          "upper": 409000
        },
        "confidence": "medium",
        "coordinates": {
          "latitude": 47.3968601,
          "longitude": 8.5153549
        },
        "currency": "EUR",
        "scores": {
          "location": 0.562
        }
      }
    ]
  ],
}

To access the value of the "upper" within "PriceRange", we can use the following code. And the expected result would be 409000.

// The first element of a JavaScript object array is always 0.
console.log(dataset.valuations[0]?.[0].salePriceRange.upper);

Method 3

Still confused about how to access the first element of a JavaScript object array? We will give you another example here. It's much easier than you think.

var req = { mandrill_events: [{"event":"inbound","ts":0123456789}] };

In the above source, mandrill_events[0] is used to get the first element, '['. Moreover, if you're stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":0123456789}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];


Leave a reply



Submit