Jan Jan - 7 months ago 16
Javascript Question

Setting up a object literal array to pass values to a server

I am passing a large number of variables to a http server. Instead of writing a long command prompt, I want to set up the variables as a object literal. If I set it up statically it works fine. But I want to populate the object in a loop.
This works:

var data= { T1: 123,
R1: 'L',
T2: 3434,
R2: 'R'};

$.post(url,data, get_outcome);


But I want to write a loop that does this, and I need to understand how I would populate the object literal with my variable names and values. (the example is just to demonstrate) If I try it this way it fails:

var data=[];
data.push({T1: 123});
data.push({T2: 3434});
data.push({R1: 'L'});
data.push({R2: 'R'});

$.post(url,data, get_outcome);


I have even tried this:

var data=[];

var a,val,name;
name={"T1","T2","R1","R2"};
val={"123","3434","L","R"};
for(a=0;a<4;a++){
data.push({name[a]:val[a]});
}
$.post(url,data,get_outcome);


The final function should work like this:

function Save(var values, var val){
var a,name;
var data=[];
for(a=0;a<values;a++){
name="T"+(a+1);
data.push({name: val[a]});
}
$.post(url,data,get_outcome);
}


What am I doing wrong ?

I implemented the solution suggested by Rajiv as follows; and now I get null values at the server.

function save(){
var data=[];

function dataPush(name, val) {
var obj = {};
obj[name] = val;
data.push(obj);
}

dataPush('T1',123);
dataPush('T2',3123);


for(a=2;a<32;a++){
temp="T"+(a+1);
dataPush(temp,T[a]);
temp="R"+(a+1);
dataPush(temp,R[a]);
}


$.post(url,data, get_outcome);
}

Answer
       var arry = [];
       function dataPush(name, val) {
            var obj = {};
            obj[name] = val;
            arry.push(obj);
        }

        KeyName =["T1","T2","R1","R2"];
        KeyVal = ["123", "3434", "L", "R"];
        for (var i = 0; i < KeyName.length; i++) {
                dataPush(KeyName[i], KeyVal[i]);
        }
        console.log(arry);

After that used this array

Comments