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

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 }))
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');

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.