Adding elements to object

Adding elements to object

I need to populate a json file, now I have something like this:

And I need to add another “element”. My first step is putting that json in a Object type using cart = JSON.parse, now I need to add the new element.
I supposed I must use cart.push to add another element, I tried this:
var element = {};
element.push({ id: id, quantity: quantity });

But I got error “Object has no method push” when I try to do element.push, and I think I’m doing something VERY wrong because I’m not telling the “element” anywhere.
How can I do that?
Edit: sorry to all I had a LOT of confusion in my head.
I thought I can get only object type when taking data from JSON.parse, but I get what I put in the JSON in the first place.
Putting array instead of object solved my problem, I used lots of suggestions got here too, thank you all!


Solution 1:

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

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

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

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

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 

Solution 2:

With that row

var element = {};

you define element to be a plain object. The native JavaScript object has no push() method. To add new items to a plain object use this syntax:

element[ yourKey ] = yourValue;

On the other hand you could define element as an array using

var element = [];

Then you can add elements using push().

Solution 3:

If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:

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

This allows you to add multiple items to the cart like so:

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

// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }

Solution 4:

you should write var element = [];
in javascript {} is an empty object and [] is an empty array.

Related:  Why is i— faster than i++ in loops? [duplicate]

Solution 5:

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

Solution 6:

Try this:

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