Categories
JavaScript Answers

How to create multi-dimensional associative arrays in JavaScript?

Spread the love

Sometimes, we want to create multi-dimensional associative arrays in JavaScript.

In this article, we’ll look at how to create multi-dimensional associative arrays in JavaScript.

How to create multi-dimensional associative arrays in JavaScript?

To create multi-dimensional associative arrays in JavaScript, we can create a nested object.

For instance, we write

const myObj = {
  fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 },
  mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 },
  sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 },
};

console.log(myObj["fred"]["apples"]);

to create the myObj object.

In it, we add the fred, mary and sarah properties.

And we set them to objects with the apples, oranges, bananas and melons properties.

Then we get a nested property with myObj["fred"]["apples"].

Conclusion

To create multi-dimensional associative arrays in JavaScript, we can create a nested object.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.