0

I'm trying to use JS to build a JSON array that looks very much like this:

{  
   "someKey":"someValue",
   "lines":{  
         "1": {
            "someKey": "someValue"
         },
         "2" {
            "someKey": "someValue"
         },
   }

}

Here's my JavaScript:

var myArray = {
    someKey: "someValue",
    lines: []
};


var count = 0;  

$('.class_that_exists_twice').each(function() {

count ++;           

    myArray.lines[count] = {
    someKey: "someValue",
    };

});

However, the array that is returned looks wrong. Any ideas what I'm doing wrong? (Please let me know if I should post the array as well)

Thank you very much!

3
  • 3
    Sample isn't an array at all, it's an object literal. What is this to be used for? An actual array might be easier to work with Commented Oct 20, 2015 at 17:32
  • It's supposed to become a JSON array to use later in PHP, I forgot mentioning that I use JSON.stringify later in order to convert to a JSON array. Commented Oct 20, 2015 at 17:35
  • to do what in php, don't need to add index to javascript object as property key to use it as indexed array in php Commented Oct 20, 2015 at 17:37

2 Answers 2

1

What you are trying to create is not an array but an object. So it should be like this:

var myArray = {
  someKey: "someValue",
  lines: {}
};

The rest looks fine

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

Comments

1

In the first JSON lines is an object. If you want to get your JSON to look like that you could do this:

var myArray = {
    someKey: "someValue",
    lines: {}
};

$('.class_that_exists_twice').each(function(index, obj) {         
    myArray.lines[index] = {
        someKey: "someValue",
    };
});

Fiddle: http://jsfiddle.net/g1pseum6/

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.