Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an array element inside JSON Object

Unintentionally, In my project I had used the following code and I was surprised to see that is working:

HTML

<span id="output"></span>

Javascript

var myObject = {
  'a': '----First---',
  'b': '----Second---',
  'c': '----Third----'
};

var myArray = ['a'];

// First Case
output.innerHTML = myObject[myArray];

var myArray2 = ['b'];

// Second Case
output.innerHTML += myObject[myArray2];

var myArray3 = ['a', 'b'];

// Third Case 
output.innerHTML += myObject[myArray3];

Output

----First-------Second---undefined

Jsbin Link: http://jsbin.com/godilosifu/1/edit?html,js,output

I am directly accessing array reference within Object which should be undefined in all the cases but strangely When array is of Size 1, it always gets the first element and use that as the object key.

I just want to know what is this concept called and why is this happening ?

like image 917
Sachin Avatar asked Mar 12 '26 01:03

Sachin


1 Answers

Because the property name has to be a string, it is type cast into one using the toString() method. The reason that your third example is undefined is that ['a', 'b'].toString() equals 'a,b', which is not a property in your object.

Property names

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Worth noting is that in ECMAScript 6, there is a new collection type called Map, which allows you to use any object as a key without type coercion.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

like image 137
Drenmi Avatar answered Mar 13 '26 14:03

Drenmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!