Adición de elementos al objeto


Necesito rellenar un archivo json, ahora tengo algo como esto:

{"element":{"id":10,"quantity":1}}

Y necesito añadir otro "elemento". Mi primer paso es poner ese json en un tipo de objeto usando cart = JSON.parse, ahora necesito agregar el nuevo elemento. Supuse que debo usar cart.push para agregar otro elemento, probé esto:

var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);

Pero tengo el error "El objeto no tiene método push" cuando intento hacer element.push, y creo que estoy haciendo algo MUY mal porque no estoy diciendo el "elemento" en ninguna parte.

¿Cómo puedo hacer ¿eso?

Edit: Lo siento por todo lo que tenía un MONTÓN de confusión en mi cabeza.

Pensé que solo puedo obtener el tipo de objeto cuando tomo datos de JSON.parse, pero en primer lugar obtengo lo que puse en el JSON.

Poniendo matriz en lugar de objeto resuelto mi problema, He utilizado un montón de sugerencias que tengo aquí también, gracias a todos!

Author: ata, 2013-01-09

12 answers

Su elemento no es una matriz, sin embargo, su carrito debe ser una matriz para soportar muchos objetos de elemento. Ejemplo de código:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

Si desea que cart sea una matriz de objetos en la forma { element: { id: 10, quantity: 1} }, realice:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() fue mencionado como una preocupación en el "comentario":

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]" 
 194
Author: Konstantin Dinev,
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
2013-01-09 12:06:41

Con esa fila

var element = {};

Se define element como un objeto plano. El objeto JavaScript nativo no tiene un método push(). Para agregar nuevos elementos a un objeto plano use esta sintaxis:

element[ yourKey ] = yourValue;

Por otro lado, se podría definir element como una matriz utilizando

var element = [];

Luego puede agregar elementos usando push().

 102
Author: Sirko,
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
2013-01-09 11:57:45

Si el carrito tiene que almacenarse como un objeto y no como un array (Aunque yo recomendaría almacenarlo como un []) siempre puede cambiar la estructura para usar el ID como clave:

var element = { quantity: quantity };
cart[id] = element;

Esto le permite agregar varios artículos al carrito de la siguiente manera:

cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};

// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }
 17
Author: Craig MacGregor,
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
2013-01-09 12:21:06

Debes escribir var element = [];
en javascript {} es un objeto vacío y [] es una matriz vacía.

 5
Author: shift66,
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
2013-01-09 11:56:03
cart.push({"element":{ id: id, quantity: quantity }});
 4
Author: Cris,
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
2013-01-09 11:58:04

Prueba esto:

var data = [{field:"Data",type:"date"},  {field:"Numero",type:"number"}];

var columns = {};

var index = 0;

$.each(data, function() {

    columns[index] = {
        field : this.field,
        type : this.type
    };

    index++;
});

console.log(columns);
 3
Author: user3910831,
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
2016-06-03 18:46:39
function addValueInObject(object, key, value) {
    var res = {};
    var textObject = JSON.stringify(object);
    if (textObject === '{}') {
        res = JSON.parse('{"' + key + '":"' + value + '"}');
    } else {
        res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
    }
    return res;
}

Este código se trabaja.

 2
Author: pashifika,
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-07-20 13:57:08
 function addValueInObject(value, object, key) {

        var addMoreOptions = eval('{"'  + key + '":' +  value + '}');

        if(addMoreOptions != null) {
            var textObject = JSON.stringify(object);
            textObject = textObject.substring(1,textObject.length-1);
            var AddElement = JSON.stringify(addMoreOptions);
            object = eval('{' + textObject +','+  AddElement.substring(1,AddElement.length-1) + '}');
        }
        return object;
    }

addValueInObject('sdfasfas', yourObject, 'keyname');

O:

var obj = {'key':'value'};

obj.key2 = 'value2';
 1
Author: Ivan Ferrer,
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
2016-05-30 19:56:05

Si alguien viene buscando crear un JSON similar, simplemente sin usar cart como una matriz, aquí va:

Tengo una matriz de objetos myArr como:

var myArr = [{resourceType:"myRT",
            id: 1,
            value:"ha"},
            {resourceType:"myRT",
            id: 2,
            value:"he"},
            {resourceType:"myRT",
            id: 3,
            value:"Li"}];

E intentaré crear un JSON con la siguiente estructura:

{
 "1":{"resourceType":"myRT","id":"1","value":"ha"},
 "2":{"resourceType":"myRT","id":"2","value":"he"},
 "3":{"resourceType":"myRT","id":"3","value":"Li"}
}

Simplemente puedes hacer -

var cart = {};
myArr.map(function(myObj){
                    cart[myObj.id]= myObj;
                    });
 1
Author: Saad Patel,
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-06-19 10:31:07

Push es un método de matrices ,por lo que para object puede obtener el índice del último elemento, y probablemente puede hacer el mismo trabajo que push for object como se muestra a continuación

var lastIndex = Object.keys(element)[Object.keys(element).length-1];

Luego agregue el objeto al nuevo índice del elemento

element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };
 0
Author: ganesh,
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-08-11 11:37:40

Si no diseña para hacer loop con en JS, por ejemplo, pase a PHP para hacer loop por usted

let decision = {}
decision[code+'#'+row] = event.target.value

Este concepto puede ayudar un poco

 0
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
2017-09-19 11:43:45

Para cualquiera que todavía esté buscando una solución, creo que los objetos deberían haber sido almacenados en una matriz como...

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

Entonces cuando quieras usar un elemento como un objeto puedes hacer esto...

var element = cart.find(function (el) { return el.id === "id_that_we_want";});

Poner una variable en "id_that_we_want" y darle el id del elemento que queremos de nuestro array. Se devuelve un objeto "elemnt". Por supuesto, no tenemos que identificarnos para encontrar el objeto. Podríamos usar cualquier otra propiedad para hacer el hallazgo.

 0
Author: Dave,
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-06 07:51:45