How to access an array of objects in JavaScript | Example code

  • by

Using object name with value index and key can access an array of objects in JavaScript. Let’s see nested data structure containing objects and arrays.

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

Extract the information, i.e. access a specific or multiple values (or keys).

data.items[1].name

or

data["items"][1]["name"]

Both ways are equal.

Example access array of objects in JavaScript

Simple HTML example code.

<!DOCTYPE html>
<html>
<body>
  <pre id="data"></pre>
  <script>

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

  console.log(data.code)
  console.log(data.items[1].name)
</script>

</body>
</html>

Output:

How to access an array of objects in JavaScript

How to access and process nested objects, arrays or JSON?

Answer: JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.

(Plain) Objects have the form

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

Arrays have the 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”.

Properties can be accessed either using dot notation

const value = obj.someProperty;

or 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];

Source & full read: https://stackoverflow.com/questions/11922383/

Do comment if you have any doubts or suggestions on this JS 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.