Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access object property with an array?

Can somebody explain the behaviour of the following code?

let obj = {a:1, b:2}
let i = ['a']
console.log(obj[i])
>> 1

Why is it that even an array can be used to access a property inside an object? As a side note this only works with an array of length 1. I have tried researching this but there's no documentation as far as I know that explains why this should work.

like image 428
dazzaondmic Avatar asked Mar 12 '19 11:03

dazzaondmic


People also ask

Can object properties be arrays?

Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.

How do you access an array of objects?

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

Can you have objects in an array?

Storing Objects in an arrayYes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.


1 Answers

Property names are always strings or symbols.

If you pass something which isn't a string or symbol, it gets converted to a string.

The default toString() method on an array is roughly:

String.prototype.toString = function () { return this.join(","); }

So ['a'] gets converted to 'a'.

As a side note this only works with an array of length 1.

It works fine with arrays that are longer. You just need a matching value:

const o = {
    "a,b": "Hello"
}
const a = ["a", "b"];
console.log("" + a);
console.log(o[a]);

And since any object can be converted to a string, and you can customise the toString method, you can do really weird things:

const data = {
  "42": "Hello"
}

class Weird {
    constructor(x) {
        this.x = x;
    }
    toString() {
        return this.x + 40;
    }
}

const w = new Weird(2);
console.log(data[w]);

(Note that doing really weird things is usually a stupid idea that makes it hard to debug your own code two weeks later).

like image 113
Quentin Avatar answered Sep 22 '22 02:09

Quentin