Homer Homer - 5 months ago 10
Javascript Question

Push objects to array and get the array content

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"}, ...]

Answer

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(/{"(\w+)":/g,'{$1:'));
Comments