Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript convert an array of one string to a string, when used as an object key? [duplicate]

Tags:

I ran into a scenario where JavaScript behaves in a way that is somewhat baffling to me.

Let's say we have an object with two keys foo & bar.

a = { foo: 1, bar: 2 } 

Then, I have an array of strings, in this case one 'foo'

b = ['foo'] 

I would expect the following:

a[b] == undefined a[b[0]] == 1 

BUT, this is what happens:

a[b] == 1 a[b[0]] == 1 

Why does JavaScript convert ['foo'] -> 'foo' when used as a key?

Does anyone out there know the reason?

How can this be prevented?

let a = { foo: 1, bar: 2 }  let b = ['foo']    console.log(a[b] == 1)    // expected a[b] to be undefined  console.log(a[b[0]] == 1)  // expected a[b] to be 1
like image 615
tompos Avatar asked Sep 15 '19 06:09

tompos


People also ask

Why does changing an array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.

Which method converts an array to string in JavaScript?

toString() The toString() method returns a string representing the specified array and its elements.

Can we convert array to string in JavaScript?

For some specific functions, arrays are converted into strings. Therefore, in JavaScript, a defined method is used for the conversion of arrays into a string. JavaScript allows returning the values of an array into a string by using the “toString()” method.

How do I convert a JavaScript object array to a string array of the object attribute I want?

Stringify a JavaScript ArrayUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(arr);


1 Answers

All the object keys are string, so it eventually convert everything you place inside [] (Bracket notation) to string, if it's an expression it evaluates the expression and convert it's value to string and use as key

console.log(['foo'].toString())

Have a look at this example to understand, here [a] eventually converts a toString using a.toString() and then set it as key to b object

let a = { a : 1}    let b = {    [a] : a  }    // object converted to string  console.log(a.toString())    // object built using [] computed property access  console.log(b)

How can i stop this

In practical scenarios you should never do this, but just to illustrate, you can intercept or override the toString method of your object and return value as string with [] around:

let a = { foo: 1, bar: 2 }    let b = ['foo']  b.toString = function() {    let string = this.join(',')    return "[" + string  + "]"  }    console.log(b.toString())  console.log(a[b])
like image 134
Code Maniac Avatar answered Sep 23 '22 20:09

Code Maniac