user1665355 user1665355 - 23 days ago 5
Javascript Question

Concatenate array into string

I have this:

var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";


And I want to get the string:

"first":"$firstelement","second": "$secondelement"


How can I do it?

Answer

What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.

You should be using an object instead, and if you want a string, you can stringify it as JSON

var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";

var str = JSON.stringify(myobject);

console.log(str)