0

I am trying to make this javascript variable with some data from an array , but i cant figure out the right syntax to make this work..

certifications will be "Win7,Win8,PDI"

var myArray = certifications.split(",");

var data = "[{" +
        for (var i in myArray)
        " "id":i,"text":myArray[i]}, " +
        "}]";

I'm hoping to get my data variable to look something like:

var data = "[{"id":0,"text":Win7},{"id":1,"text":Win8},{"id":2,"text":PDI}]";
3
  • Don't try to create object literal strings. Just create real objects! Commented Sep 23, 2014 at 19:22
  • 2
    No, it doesn't. Why would you? If you want to create JSON strings, use JSON.stringify() on real objects and arrays. Commented Sep 23, 2014 at 19:24
  • your right. thanks bergi Commented Sep 23, 2014 at 19:27

2 Answers 2

5

Try this:

var data = JSON.stringify(certifications.split(",").map(function(value, index) {
    return {
        id: index,
        text: value
    };
}));
Sign up to request clarification or add additional context in comments.

Comments

2

Maybe += is what your looking for:

var certifications = "Win7,Win8,PDI";
var myArray = certifications.split(",");
var data = "[{";

for (var i in myArray) {
    data += " " +
    "id" +":"+i+","+
    "text" + ":"+myArray[i]+"}, ";
}
data += "}]";

2 Comments

Yes, that might work, but you need to ensure that i and myArray[i] are properly escaped
@friedi has a much better solution. Hopefully he uses that instead of making his own JSON.

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.