0

I have this array:

var array = {
item: 'value',
subArray: []
}

I would like to use a $.each function to loop through some data and push key:value values into the subArray. After pushing the array should look like this:

var array = {
item: 'value',
subArray: [item: 'value', item: 'anothervalue', ...]
}

I'm currently using this inside my $.each loop:

$('class').each(function() {
    array.subArray.push({ 'item': $(this).html() });
});

However, the current result is this:

var array = {
item: 'value',
subArray: [{item: 'value'}, {item: 'anothervalue'}, ...]
}

Any advice would be appreciated. Thanks!

1
  • 1
    Firstly, you have an object not an array. Secondly, javascript does not have associative arrays. The closest you can get is an array of objects, which is what your final example is. Commented Mar 14, 2016 at 20:22

1 Answer 1

2

Your desired result of subArray: [item: 'value', item: 'anothervalue', ...] is invalid. Arrays are not key/val pairs - that's an object. The result you are getting is the actual result you want.

[{item: 'value'}, {item: 'anothervalue'}, ...]

Is a perfectly valid array of objects. To add to the confusion of your code above:

var array = {
    item: 'value',
    subArray: []
}

The above is not an array - it's an object with two properties (item, and subArray)

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

4 Comments

Thanks for your answer. The thing is that later on in the function I convert my array to JSON, and the JSON should look like this: subArray{"item": "value", "item": "anothervalue"} - any idea how to achieve this?
@Frank that JSON structure is completely invalid as you have duplicate item keys within it.
@RoryMcCrossan: Thanks for letting me know, I'll have to change a few things :)
@Frank -- Why? You're converting to something that can't be converted to anything else - as it's invalid.

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.