2

How can I push an object into a jquery data() object that is an array. I want to end up with the data property numbers containing an array of objects, that I acquire by looping through some html of a particular class. I don't understand how I can push each object into the array.

My first question is, if I have some data in an object, how can I look at the whole object. It seems like it used to be that I could do

$('#div1').data('values', {'one' : 'UNO', 'two' : 'DUE'}); console.log($('#div1').data('values'))

and Chrome would give me a little expandable object to look at. Now I just see [object Object] I can still see them if I do

console.log($('#div1').data('values').one).

But that seems a little more inconvenient if I don't know exactly what's in the data() object. It would be useful for checking to see how close I am to achieving this.

Once I assign all my data to their respective objects,

$(document).ready(function(){
  $('#div1').data('values', {'one' : 'UNO', 'two' : 'DUE'});
  $('#div2').data('values', {'three' : 'TRE', 'four' : 'QUATTRO'});
  $('#div3').data('values', {'five' : 'CINQUE', 'six' : 'SEI'});
  $('#div4').data('values', {'seven' : 'SETTE', 'eight' : 'OTTO'});
}); 

how can I loop through these objects (all with a shared class add) and put the objects they contain in data.values into another data() object? Here I'm trying to do it on the body's data object, numbers:

  `$('body').data('numbers', []);`

so that

$('body').data('numbers') =

['div1': {
    'one': 'UNO',
    'two': 'DUE'
},
'div2': {
    'three': 'TRE',
    'four': 'QUATTRO'
},
'div3': {
    'five': 'CINQUE',
    'six': 'SEI'
},
'div4': {
    'seven': 'SETTE',
    'eight': 'OTTO'
}]

my attempt has failed:

    $('.add').each(function (index, element) {
        $('body').data(numbers, {
            element.attr('id'): element.data('values')
        //could not understand how to use push here, though it seems likely that's the answer
     });

jsbin

1252748
  • 14,597
  • 32
  • 109
  • 229
  • 1
    Javascript does not literally have "associative arrays". Do you want your final result to be A. An un-ordered collection of name/value pairs (object) or B. An ordered list of values (Array)? – Aaron Kurtzhals Feb 06 '13 at 16:44
  • @AaronKurtzhals You're right. I don't know why I set it up as an array. An object is what I was after. Thanks. – 1252748 Feb 06 '13 at 16:46

1 Answers1

4

JavaScript does not have associative arrays so you have to use an Object. Then use bracket notation for the property (key) names:

var values = {};
$('.add').each(function (index, element) {
    values[element.id] = $(element).data('values');
});
$('body').data('numbers', values);

jsBin

About your [object Object], you may be accidentally doing string concatenation with the object before outputting it to the console, else it is a bug in your Chrome console.

Using an array you can use .push to push items onto the end of the array:

var values = [];
$('.add').each(function (index, element) {
    values.push( $(element).data('values') );
});

Bin

After having the array initialized and stored inside the element's .data(), you can later push items into it by simply grabbing a reference to the Array object and calling .push() on it:

var values = [];
$('.add').each(function (index, element) {
    values.push( $(element).data('values') );
});
$('body').data('numbers', values);

$('body').data('numbers').push({'nueve': 'nine'});
//logs "nueve" too as Array/Objects/Functions are passed by reference and the
//previous command pushed an item into the Array object referenced ("stored")
//in the $('body').data('numbers')
console.log( $('body').data('numbers') );

Bin

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • Thanks! Why do you need to surround `element` with a jquery wrapper? – 1252748 Feb 06 '13 at 16:48
  • Because [`.each`](http://api.jquery.com/each/)'s second parameter returns a [DOM Element](https://developer.mozilla.org/en-US/docs/DOM/element) reference which does not have a `.data()` method. `=]` So you have to wrap it inside a jQuery object to call the [`.data()`](http://api.jquery.com/data/) method on it. – Fabrício Matté Feb 06 '13 at 16:49
  • I'm curious if it's possible to do with an array. I do not necessarily need the objects named div1, div2, div3. And would doing it in an array give me the availability to simply push a new object onto the end? – 1252748 Feb 06 '13 at 16:55
  • Using an array you can use [`.push`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push) to push items onto the end of the array: http://jsbin.com/ababoy/7/edit – Fabrício Matté Feb 06 '13 at 16:57
  • @thomas Updated answer, check if it is useful. `=]` – Fabrício Matté Feb 06 '13 at 17:07
  • yes. Fabrício Matté is right. Modified the same concept with demanded output, please refer http://jsbin.com/ababoy/12/edit – vrluckyin Feb 06 '13 at 17:14
  • Oh thanks @vrluckyin, I didn't notice the output wasn't in the correct format. Though, the desired output (having an array with named properties) can't* be done - actually it *could* be done setting custom properties in the Array object but then you'd rather be using a plain object for that which is what I've done. – Fabrício Matté Feb 06 '13 at 17:28
  • That's really great, thanks! Before it was showing up in the console as a string like : `({ div1: { one: "UNO", two: "DUE" }, div2: { three: "TRE", four: "QUATTRO" }, div3: { five: "CINQUE", six: "SEI" }, div4: { seven: "SETTE", eight: "OTTO" } })` but now they're expandable objects. How'd you do that! – 1252748 Feb 06 '13 at 17:31
  • @thomas All objects are expandable to me on Chrome http://i.imgur.com/0dv8vpo.png – Fabrício Matté Feb 06 '13 at 17:37
  • That's what mine used to look like. Then something changed and everything is just [object Object] most of the time :( I can't thank you enough for your help today. Cheers! – 1252748 Feb 06 '13 at 17:39
  • That's weird, `[object Object]` shouldn't happen when you do `console.log({})` except in IE Dev tools or if you accidentally do concatenation like `console.log({}+'')`, maybe try reinstalling/updating Chrome. – Fabrício Matté Feb 06 '13 at 17:46