[javascript] Adding elements to object

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

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

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 });
cart.push(element);

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!

This question is related to javascript json object

The answer is


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


 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');

OR:

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

obj.key2 = 'value2';

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 } }

For anyone still looking for a solution, I think that the objects should have been stored in an array like...

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

Then when you want to use an element as an object you can do this...

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

Put a variable at "id_that_we_want" and give it the id of the element that we want from our array. An "elemnt" object is returned. Of course we dont have to us id to find the object. We could use any other property to do the find.


This is an old question, anyway today the best practice is by using Object.defineProperty

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

if you not design to do loop with in JS e.g. pass to PHP to do loop for you

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

this concept may help a bit


I was reading something related to this try if it is useful.

1.Define a push function inside a object.

let obj={push:function push(element){ [].push.call(this,element)}};

Now you can push elements like an array

obj.push(1)
obj.push({a:1})
obj.push([1,2,3])

This will produce this object

obj={
 0: 1
 1: {a: 1}
 2: (3) [1, 2, 3]
 length: 3
}

Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push() function


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().


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
    };

    index++;
});

console.log(columns);

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;
}

this code is worked.


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

To append to an object use Object.assign

var ElementList ={}

function addElement (ElementList, element) {
    let newList = Object.assign(ElementList, element)
    return newList
}
console.log(ElementList)

Output:

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


If anyone comes looking to create a similar JSON, just without using cart as an array, here goes:

I have an array of objects myArr as:

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

and I will attempt to create a JSON with the following structure:

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

you can simply do-

var cart = {};
myArr.map(function(myObj){
                    cart[myObj.id]= myObj;
                    });

push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below

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

then add object to the new index of element

element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };

Adding new key/pair elements into the original object:

const obj = { a:1, b:2 }
const add = { c:3, d:4, e: ['x','y','z'] }

Object.entries(add).forEach(([key,value]) => { obj[key] = value })

obj new value:

{a: 1, b: 2, c: 3, d: 4, e: ["x", "y", "z"] }

My proposition is to use different data structure that proposed already in other answers - it allows you to make push on card.elements and allow to expand card properties:

_x000D_
_x000D_
let card = {
  elements: [
    {"id":10,"quantity":1}
  ],

  //other card fields like 'owner' or something...
}

card.elements.push({"id":22,"quantity":3})

console.log(card);
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor