0

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

3
  • 1
    Where is json2 defined? Looks like some code is missing here. Commented Dec 23, 2013 at 17:16
  • 3
    And sigh there's no JSON anywhere in this question. Those are just JavaScript objects. Commented Dec 23, 2013 at 17:17
  • 1
    I've removed the JSON tag since your question doesn't seem to be related to the JSON data format at all. Commented Dec 23, 2013 at 17:19

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

This is part of it, but the whole series of code seems suspect.
I know the code is insufficient but just forget about those json2. i just want to push on an array element which is a json object, how could i do that?
Provided you have an array object which is the only object that supports push natively the use push as shown.

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.