Erik Erik - 9 days ago 7
Javascript Question

Why does array's object property correctly access to the value?

I have the following object:

var obj = {
"Name of something": {
"key1": "value1",
"key2": "value2"
}
};


I wonder why the following code works properly?

var title = Object.keys(obj);
console.log(obj[title]) // {"key1": "value1", "key2": "value2"}


How does
title
access to
Name of something
object's property of
obj
?
title
is array is it?

Answer

The object has only one key, so Object.keys returns the array

["Name of something"]

If you convert that array to a string, which is what happens when you pass it as a key

["Name of something"].toString()

You get

"Name of something"

Which is the key for your object, so end up with

obj["Name of something"] // returns {"key1": "value1", "key2": "value2"}
Comments