Agregar elementos a un objeto a través de la.método push()


Estoy haciendo un bucle a través de algunos elementos de entrada de tipo 'checkbox'. Después de eso, estoy agregando valores y atributos comprobados a una matriz. Este es mi código:

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

Esto funciona bien, pero me pregunto si puedo hacer exactamente lo mismo con .método push () en Jquery?

He intentado algo como esto, pero no funciona:

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

Editar:

Estaba tratando de usar .método push () en el objeto, pero .push() es en realidad solo un método de Objeto Array.

Author: dperitch, 2011-08-31

5 answers

.push() es un método de la Construido-en la serie de Objeto

No está relacionado con jQuery de ninguna manera.

Estás definiendo un Objeto literal con

// Object
var stuff = {};

Puede definir un Array literal como este

// Array
var stuff = [];

Entonces

stuff.push(element);

Los arrays en realidad obtienen su sintaxis de corchetes stuff[index] heredada de su padre, el Objeto. Esta es la razón por la que usted es capaz de usarlo de la manera que está en su primera ejemplo.

Esto se usa a menudo para una reflexión sin esfuerzo para acceder dinámicamente a las propiedades

stuff = {}; // Object

stuff['prop'] = 'value'; // assign property of an 
                         // Object via bracket syntax

stuff.prop === stuff['prop']; // true
 120
Author: jondavidjohn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-17 22:35:00

Así que es fácil)))

Mira esto...

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

Y tendrás:

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

O:

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

Tendrás:

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

O:

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

Tendrás:

Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
 12
Author: Иван Олейник,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-06 13:24:14

stuff es un objeto y push es un método de una matriz. Así que no puedes usar stuff.push(..).

Digamos que define stuff como una matriz stuff = []; luego puede llamar al método push en él.

Esto funciona porque el objeto[clave/valor] está bien formado.

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

Mientras que esto no funcionará porque el objeto no está bien formado.

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

Esto funciona porque estamos tratando stuff como una matriz asociativa y valores añadidos a it

stuff[$(this).attr('value')] = $(this).attr('checked');

 12
Author: ShankarSangoli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-25 08:41:41

Esto es realmente fácil: Ejemplo

//my object
var sendData = {field1:value1, field2:value2};

//add element
sendData['field3'] = value3;
 2
Author: Abraham Rosales,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-17 20:51:46

Otra forma de hacerlo sería:

stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});

Lea más aquí: Objeto.asignar()

 1
Author: Niklas Jarl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-04 17:43:48