max imax
max imax

Reputation: 2261

add item to an array of json objects

I want to add a value to specific field of my array which is a json object. in other words i want to append to a json object which is a field of another array.

var cdata = new Array();
 for (i in json2) {
     for (j in json2[i]) {
         //here i get error:
         cdata[j].push({
             'x': json2[i].timestamp,
             'y': json2[i][j]
         });
     };
 };

but i get Uncaught TypeError: Cannot call method 'push' of undefined error.

thanks in advance

Upvotes: 0

Views: 84

Answers (1)

Captain John
Captain John

Reputation: 2001

You are calling push on an array element referred to by the index j as follows cdata[j]

You should call

cdata.push({
         'x': json2[i].timestamp,
         'y': json2[i][j]
     });

Additionally - thanks to commenter - looking at the way you are iterating through the array json2 it doesn't seem right. We could do with seeing json2 to fully answer this one.

The line:

json2[i].timestamp

Suggests json2 is an array of objects

However the line:

json2[i][j] 

suggests json2 is a multi-dimensional array.

See this post: How can I create a two dimensional array in JavaScript?

HTH

Upvotes: 4

Related Questions