Skip to content

How to access a nested array of objects in JavaScript | Example code

You can access a nested array of objects either using dot notation or bracket notation. JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of an object.

(Plain) Objects form

{key: value, key: value, ...}

Arrays form

[value, value, ...]

Both arrays and objects expose a key -> value structure. Keys in an array must be numeric, whereas any string can be used as a key in objects. The key-value pairs are also called the “properties”.

Access Properties using dot notation

const value = obj.someProperty;

Access array using bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:

// the space is not a valid character in identifier names
const value = obj["some Property"];

// property name as variable
const name = "some Property";
const value = obj[name];

For that reason, array elements can only be accessed using bracket notation:

const value = arr[5]; // arr.5 would be a syntax error

// property name / index as variable
const x = 5;
const value = arr[x];

What’s about JSON?

JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects.

Source: stackoverflow.com/

Example access a nested array of objects in JavaScript

Simple example code accessing nested objects JavaScript. The value is an array, to access its second element, use bracket notation and we use dot notation again to access the name property.

<!DOCTYPE html>
<html>
<body>

  <script>
   const data = {
    code: 42,
    items: [{
      id: 1,
      name: 'foo'
    }, {
      id: 2,
      name: 'bar'
    }]
  };

  const item_name = data.items[1].name;
  
  console.log(item_name)
  console.log(data.items[1])
</script>

</body>
</html>

Output:

How to access a nested array of objects in JavaScript

Simple explanation:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

/*
 1. `data` is object contain `items` object*/
console.log(data);

/*
 2. `items` object contain array of two objects as elements*/
console.log(data.items);

/*
 3. you need 2nd element of array - the `1` from `[0, 1]`*/
console.log(data.items[1]);

/*
 4. and you need value of `name` property of 2nd object-element of array)*/
console.log(data.items[1].name);

Do comment if you have any doubts or suggestions on this JS nested array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading