user1934044 user1934044 - 15 days ago 6
Javascript Question

programatically create json array object in javascript

My code is

var arr=[];
$.post( "/reports/search", { query:'*'},function(data) {
for(var i=0;i<data.length;i++)
{
arr[i].value=data[i].name;
arr[i].data=data[i].id;
}

},'json');


I want to create a json array variable and i want the resut like below

arr=[ {"value":"aaa",data:"1"},
{"value":"bbb",data:"2"},
{"value":"ccc",data:"3"}

]


How to do it in javascript

Answer

This will work in all modern browsers:

var arr = data.map(function(row){return {value: row.name, data: row.id});

In ES6 (with deconstruction and renaming):

var arr = data.map(({name: value, id: data}) => ({ value, data }))
Comments