1

I get results from Ajax call and want to push it to an array as objects;

This is my try:

var myList = [""];

$.ajax({
    url: 'list.json',
    dataType: 'json',
    success: function (data) {

        for (var i = 0; i < data.length; i++) {
            myList.push({
                id: data[i].id,
                text: data[i].text
            });
        }
        console.log(myList);

    }
});

The output I get is:

["",Object, Object, Object, ...]

I'm wondering how can I get the output like this:

["", {id:"id", text:"text"}, {id:"id", text:"text"}, ...]
1
  • 2
    JSON.stringify() Commented Jun 21, 2016 at 15:42

2 Answers 2

3

You can use JSON.stringify() method to convert the object to JSON string.

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

UPDATE : Your question output is not a valid json, to convert into that format use String#replace method.

console.log(JSON.stringify(myList).replace(/({\s?|,\s?)"(\w+)":/g,'$1$2:'));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! ... But there's a small thing is not okay with that, it's returning BOTH the key pair between double quotes: {"id":"id"} , how can I make it surround the data only with quotes, to be {id:"id"} ?
@Homer : that's valid json... otherwise try console.log(JSON.stringify(myList).replace(/{"(\w+)":/g,'{$1:'));
Thanks again Pranav!
Would you please help in refining the replace a little, to make it replace the other key? since it's replacing the first one only! :) {id: "id", "text": "text"}
Thanks a lot! I appreciate your help!
1

Easy!

JSON.stringify(myList);

Should take care of it for you.

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.