Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items to an object through the .push() method

I'm doing a loop through few input elements of 'checkbox' type. After that, I'm adding values and checked attributes to an array. This is my code:

var stuff = {}; $('form input[type=checkbox]').each(function() {     stuff[$(this).attr('value')] = $(this).attr('checked'); }); 

This works fine, but I'm just wondering if I can do the exact same thing with .push() method in Jquery?

I've tried something like this but it doesn't work:

stuff.push( {$(this).attr('value'):$(this).attr('checked')} ); 

Edit:

I was trying to use .push() method on Object, but .push() is actually just a method of Array Object.

like image 504
dperitch Avatar asked Aug 31 '11 18:08

dperitch


People also ask

Can we use push method on object?

push can work on an object just fine, as this example shows. Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.

What push () will do?

The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

How do you push values into objects?

In order to push an array into the object in JavaScript, we need to utilize the push() function. With the help of Array push function this task is so much easy to achieve. push() function: The array push() function adds one or more values to the end of the array and returns the new length.


2 Answers

.push() is a method of the Built-in Array Object

It is not related to jQuery in any way.

You are defining a literal Object with

// Object var stuff = {}; 

You can define a literal Array like this

// Array var stuff = []; 

then

stuff.push(element); 

Arrays actually get their bracket syntax stuff[index] inherited from their parent, the Object. This is why you are able to use it the way you are in your first example.

This is often used for effortless reflection for dynamically accessing properties

stuff = {}; // Object  stuff['prop'] = 'value'; // assign property of an                           // Object via bracket syntax  stuff.prop === stuff['prop']; // true 
like image 189
jondavidjohn Avatar answered Oct 04 '22 02:10

jondavidjohn


so it's easy)))

Watch this...

    var stuff = {};     $('input[type=checkbox]').each(function(i, e) {         stuff[i] = e.checked;     }); 

And you will have:

Object {0: true, 1: false, 2: false, 3: false} 

Or:

$('input[type=checkbox]').each(function(i, e) {     stuff['row'+i] = e.checked; }); 

You will have:

Object {row0: true, row1: false, row2: false, row3: false} 

Or:

$('input[type=checkbox]').each(function(i, e) {     stuff[e.className+i] = e.checked; }); 

You will have:

Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false} 
like image 35
Иван Олейник Avatar answered Oct 04 '22 00:10

Иван Олейник