0

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?

4 Answers 4

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

ok but I do not want {} around the string and also do not want double " inside string
This is what you should want, as it's valid JSON. You can remove the curlybraces with .slice(1, -1) and you could replace the quotes with .replace(/\"/,'') but you shouldn't
0

First of all, you'd want to use an object instead of an array:

var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";

The easiest way, then, to achieve what you want is to use JSON:

var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);

Comments

0

JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

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

console.log(JSON.stringify(myarray));

Comments

-1

Use JSON.strinify()

JSON.stringify(item)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.