0

I'm trying to produce an array that looks like this:

[
      {
        "values": [ 
          [1, 0], 
          [2, -6.3382185140371], 
          [3, -5.9507873460847], 
          [4, -11.569146943813], 
          [5, -5.4767332317425], 
          [6, 0.50794682203014], 
          [7, -5.5310285460542], 
          [8, -5.7838296963382], 
          [9, -7.3249341615649], 
          [10, -6.7078630712489] 
        ]
      }
    ]  

I'm doing an array in javascript that looks like this and only produce the values, but doe not place it within "values" : []:

var myArray = new Array(10);
    for (i = 0; i < 10; i++) {
      myArray[i] = new Array(2);
      myArray[i][0] = i;
      myArray[i][1] = 5;
    }    

    var jsonEncoded = JSON.stringify(myArray);
    return jsonEncoded;

I'm sure this is an easy answer, but I'm not experience enough to know. Thanks for the help in advance.

3
  • Do the values within the arrays matter (i.e., the -6.33… part of [2, -6.33…])? Commented Jul 9, 2014 at 2:29
  • At this moment they do not, we are simply getting it to work and then will control the values later with equations. Commented Jul 9, 2014 at 2:30
  • really not clear what the question is Commented Jul 9, 2014 at 2:32

2 Answers 2

2

Here you go, you basically need to wrap your myArray in an object and put that object into another array.

var myArray = new Array(10);
for (i = 0; i < 10; i++) {
  myArray[i] = new Array(2);
  myArray[i][0] = i;
  myArray[i][1] = 5;
}
var result = [{values: myArray}];

var jsonEncoded = JSON.stringify(result);
return jsonEncoded;
Sign up to request clarification or add additional context in comments.

Comments

0

It should be

var jsonEncoded = JSON.stringify([{values:myArray}]);

There are several other, more verbose ways to do it, but that's it.

In this case, myArray is an array containing N elements, each one being an array of two numbers.

Enclosing {key : value} pairs in curly bracers { } means you're declaring an object. In this case, "values" is your key, and myArray is your value. No pun intended here, it's just that you picked a confusing keyname. Object notation in js does not require quoting the key.

Finally, enclosing the aforementioned object between brackets will result in an array whose only element is that object.

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.