How to Access an Array/Object

How can I access and process nested objects, arrays, or JSON?

Preliminaries

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

Wait... what 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 (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .

Further reading material

How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections

  • Working with Objects
  • Arrays
  • Eloquent JavaScript - Data Structures


Accessing nested data structures

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

Here is an example:

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

Let's assume we want to access the name of the second item.

Here is how we can do it step-by-step:

As we can see data is an object, hence we can access its properties using dot notation. The items property is accessed as follows:

data.items

The value is an array, to access its second element, we have to use bracket notation:

data.items[1]

This value is an object and we use dot notation again to access the name property. So we eventually get:

const item_name = data.items[1].name;

Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:

const item_name = data['items'][1]['name'];

I'm trying to access a property but I get only undefined back?

Most of the time when you are getting undefined, the object/array simply doesn't have a property with that name.

const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined

Use console.log or console.dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.

console.log(foo.bar.baz); // 42

What if the property names are dynamic and I don't know them beforehand?

If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in [MDN] loop for objects and the for [MDN] loop for arrays to iterate over all properties / elements.

Objects

To iterate over all properties of data, we can iterate over the object like so:

for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}

Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty [MDN].

As alternative to for...in with hasOwnProperty, you can use Object.keys [MDN] to get an array of property names:

Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});

Arrays

To iterate over all elements of the data.items array, we use a for loop:

for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}

One could also use for...in to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.

With the increasing browser support of ECMAScript 5, the array method forEach [MDN] becomes an interesting alternative as well:

data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});

In environments supporting ES2015 (ES6), you can also use the for...of [MDN] loop, which not only works for arrays, but for any iterable:

for (const item of data.items) {
// `item` is the array element, **not** the index
}

In each iteration, for...of directly gives us the next element of the iterable, there is no "index" to access or use.


What if the "depth" of the data structure is unknown to me?

In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.

But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.

Here is an example to get the first leaf node of a binary tree:

function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}

const first_leaf = getLeaf(root);

const root = {    leftChild: {        leftChild: {            leftChild: null,            rightChild: null,            data: 42        },        rightChild: {            leftChild: null,            rightChild: null,            data: 5        }    },    rightChild: {        leftChild: {            leftChild: null,            rightChild: null,            data: 6        },        rightChild: {            leftChild: null,            rightChild: null,            data: 7        }    }};function getLeaf(node) {    if (node.leftChild) {        return getLeaf(node.leftChild);    } else if (node.rightChild) {        return getLeaf(node.rightChild);    } else { // node must be a leaf node        return node;    }}
console.log(getLeaf(root).data);

Accessing Object Property Values Within an Array - JavaScript

You can acces items in arrays at given position by their index. In javascript indexes of arrays are starting with 0: myArray[0]. To access the property of the returned object just use dot-notation: myArray[0].myProperty.

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];
console.log(object1[1].job);

Access object inside an array - Javascript

The Problem Explained

Your JS is looking at the property on a specific character:

Take a look at the following example that will help demonstrate what is going on:

const string = 'Hello';console.log(string[0] === 'H'); // trueconsole.log('H'.key3 === undefined); // true

Javascript get value from an object inside an array

You are trying to get the value from the first element of the array. ie, data[0]. This will work:

console.log(data[0].value);

If you have multiple elements in the array, use JavaScript map function or some other function like forEach to iterate through the arrays.

data.map(x => console.log(x.value));

data.forEach(x => console.log(x.value));

How to access the objects from arrays[0] position individually?

What you have is an multidimensional array that means your array looks like this

var array = [[{ob1},{ob2}],[{ob3},{ob4}],[{ob5},{ob6}]]

To access the first object of the first array you have to get it the following way

array[0][0]

Which would print ob1. To access the first element of the third array you just have to write

array[2][0]

I added a snippet as a showcase

var array = [[{obj:1},{obj:2}],[{obj:3},{obj:4}],[{obj:5},{obj:6}]];console.log(array[0][0]);console.log(array[2][0]);

How to access array element without index ([])

You're gonna need some way to identify the object you're looking for. For example, if the object has a specific property with a specific value, you can use that to find this object in the array. To actually find the object, you can use Array.prototype.find.

For example, if you're always looking for the object with an id of 123:

const testArray = [{ id: 123 }, { id: 456 }, { id: 789 }];
const idToSearchFor = 123;
const objectWithSpecificId = testArray.find(
obj => obj.id === idToSearchFor
);

If you want to find multiple objects instead of one, you can use Array.prototype.filter:

const testArray = [{ id: 123 }, { id: 456 }, { id: 789 }];
const idsFilter = [123, 789];
const matchingObjects = testArray.filter(
obj => idsFilter.includes(obj.id)
);
console.log(matchingObjects.length); // 2

Accessing Array Object property in ES6,

You can map over the array at index [1], and use .length to get the length of the outcome array.

const data = [
[{
"id": 1,
"full_name": "jack",
"email": "carl@gmail.com",
"phone": "2123309",
"dob": "2008-06-12",
"location": "VAUGHAN",
"user_id": 1,
"created_at": "2021-10-02T09:10:04.000000Z",
"updated_at": "2021-10-02T12:16:57.000000Z"
}],
[{
"id": 1,
"price": "432.00",
"order_type": "Car Parking",
"currency": "USD",
"paid": 0,
"amount_paid": "432.00",
"overdue": "0.00",
"client_id": 1,
"user_id": 1,
"created_at": "2021-10-02T09:10:26.000000Z",
"updated_at": "2021-10-02T09:46:00.000000Z"
}, {
"id": 2,
"price": "2500.00",
"order_type": "Ramp",
"currency": "USD",
"paid": 0,
"amount_paid": "2030.00",
"overdue": "470.00",
"client_id": 1,
"user_id": 1,
"created_at": "2021-10-02T09:48:07.000000Z",
"updated_at": "2021-10-02T10:14:22.000000Z"
}, {
"id": 9,
"price": "893.00",
"order_type": "Shipping",
"currency": "CAD",
"paid": 0,
"amount_paid": "765.00",
"overdue": "128.00",
"client_id": 1,
"user_id": 1,
"created_at": "2021-10-02T10:46:45.000000Z",
"updated_at": "2021-10-02T10:54:06.000000Z"
}, {
"id": 21,
"price": "250.00",
"order_type": "Storage rent",
"currency": "USD",
"paid": 0,
"amount_paid": "0.00",
"overdue": "250.00",
"client_id": 1,
"user_id": 1,
"created_at": "2021-10-03T08:33:13.000000Z",
"updated_at": "2021-10-03T08:33:13.000000Z"
}]
]

const result = data[1].map(x => x.amount_paid);
const resultLength = result.length;

console.log("Result: ", result);
console.log("Length: ", resultLength);

JavaScript: How to access an array object inside an object

Subcategories are not being accessed as they are inside an array inside categories and won't be accessed directly.
Accessing it as categories[0].subcategories or any other valid index should do the job



Related Topics



Leave a reply



Submit