1

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

Barmar
789k57 gold badges555 silver badges669 bronze badges
asked May 8, 2014 at 9:56

2 Answers 2

3

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 }))
answered May 8, 2014 at 9:59
Sign up to request clarification or add additional context in comments.

1 Comment

BTW. if you need older browsers, just do a $.map(data, function(row) {...});
1

You need to create the object before you can assign to its properties:

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

Or you can just do all 3 steps at once by using an object literal:

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.