0

If anybody knows , please help me , i am very badly struck .

From AJAX Call i am constructing this data in my server (This data is fetched from the server so there can be any number of such rows data )

{data:[{one:"1",two:"2"},{one:"3",two:"3"}]}

My question is that , is it possible to construct a similar array inside javascript dynamically ??

For example , depending upon the number of rows , i want to construct a similar jaavscript array dynamically (For example depneding on data.length , i want to construct this type dynamically

var data = {
  jobs:[
    {one:"1",two:"2"},
    {one:"3",two:"3"}
  ]
};

Please help me .

1 Answer 1

1

This will dynamically create a list of dictionary, which is what I think you are looking for:

var row = {};
row['one'] = "1";
row['two'] = "2";
data.push(row);
row = {};
row['one'] = "3";
row['two'] = "3";
data.push(row);
// outputs [{"one":"1","two":"2"},{"one":"3","two":"3"}]
alert( JSON.stringify( data ) )
Sign up to request clarification or add additional context in comments.

3 Comments

The above one is static , i want to create it dynamically , anyways thanks for your time .
for ( var i = 0; i < data.jobs.length; i++) { jsonDatarav = '{ ' + '"one" : ' + '"' + data.jobs[i].one + '"' + ", " + '"two" : ' + '"'+ data.jobs[i].two + '"' + ' }'; } , but this is only creating one value of data only
Notice that you are building an array []. You are manually constructing a JSON a string. My method used JSON.stringify to build the array of dict. If you wish to use your string method, then you need to start 'data' with data='[', construct your row data+=jsonDatarav", append it to 'data', construct and append more to data+=',' data+=jsonDatarav and terminate with date+=']'. Otherwise, use the JSON.stringify method above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.