326

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!

4
  • 7
    possible duplicate of Add new element to existing object in JavaScript / jQuery
    – Foreever
    Commented Oct 22, 2014 at 6:30
  • Object.assign(target, source); can be used to copy all the properties from a source object to a target object. Commented Aug 25, 2019 at 12:11
  • .push gives me 'Not a function' let result = rowData.slice(); result.forEach(e =>e.push({action: 'test')}; Commented Sep 10, 2020 at 18:41
  • 1
    The title is confusing as this is about adding element to Array not to an Object. Ik that everything in js is object, but still...
    – Matt Rek
    Commented Jan 7, 2021 at 13:19

21 Answers 21

404

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 = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

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

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

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

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]" 
5
  • 3
    thank you, but my cart now is not an array and i can't do the cart.push :( i need an object to use JSON.stringify(cart) after this operation
    – HypeZ
    Commented Jan 9, 2013 at 12:03
  • @HypeZ You can still stringify cart if it is an array of objects. Commented Jan 9, 2013 at 12:04
  • thank you again! But my base data is object type cause of the "cart = JSON.parse(jsonfile)" on the beginning.. i don't think i should take the json as a object, convert it to array, add element, stringify..
    – HypeZ
    Commented Jan 9, 2013 at 12:09
  • for some reason, my object becomes filled with last element only. e.g I have 4 different items, but in an object all 4 elements are = last value solution I found is create element = {}; inside of for, then its work properly Commented Apr 29, 2020 at 21:54
  • 3
    @GorodeckijDimitrij If you're reusing the same element object and you repopulate it's keys with new values, then you would be modifying one and the same instance of element, pushing it again and again into an array. Just use a new element object for each element you're adding, which is what you've done in the scope of a for-loop. Commented May 13, 2020 at 13:38
236

The line of code below defines element as a plain object.

let element = {}

This type of JavaScript object with {} around it has no push() method. To add new items to an object like this, use this syntax:

element[yourKey] = yourValue

To put it all together, see the example below:

let element = {} // make an empty object

/* --- Add Things To The Object --- */

element['active'] = true // 'active' is the key, and 'true' is the value
console.log(element) // Expected result -> {active: true}


element['state'] = 'slow' // 'state' is the key and 'slow' is the value
console.log(element) // Expected result -> {active: true, state: 'slow'}

On the other hand, if you defined the object as an array (i.e. using [] instead of {}), then you can add new elements using the push() method.

9
  • 16
    element[ yourKey ] = yourValue; is the best way one can add element to an object. Commented Sep 5, 2018 at 6:20
  • But you can't grantee the order of the element added in the object with element[ yourKey ] = yourValue; Commented Sep 9, 2018 at 18:01
  • 2
    @Pramesh Bajracharya It doesn't ADD values to the element, it just sets the current element to that value.
    – Hasen
    Commented Jun 5, 2019 at 6:28
  • 1
    @sommesh how do you want to keep the duplicate? you could do element[ yourkey ] = [ element{yourkey], yourNewValue ];
    – Sirko
    Commented Oct 19, 2019 at 6:45
  • 1
    @sommesh this would give you a duplicate key, which by definition is not possible in a JS object. you can only collect multiple values for one key like I've shown before.
    – Sirko
    Commented Oct 19, 2019 at 7:03
34

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

2
  • 2
    This is probably the most functional way to do things, but a newcomer javascript developer will probably not understand this. Commented Jul 15, 2019 at 11:24
  • 3
    i tried it but it will override existing element, because both have same name element, so it will have the last element only. Commented Aug 1, 2019 at 8:01
26

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 } }
3
  • thank you, but my cart needs to be an object and not an array :(
    – HypeZ
    Commented Jan 9, 2013 at 14:05
  • 4
    One reason to use an object like this, is if you need to delete items. Deleting a key from an object is a lot easier than deleting a key from an array.
    – bryc
    Commented Feb 11, 2015 at 22:23
  • 3
    In case HypeZ's array comment throws anybody off, Craig's answer doesn't add an array, the brackets [] are used to access the property. Test it here on jsfiddle and read about it here at Mozilla and here's a great article at Digital Ocean that I wish I came across long ago. Commented Aug 27, 2018 at 7:33
20

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'] }
2
  • 7
    or you can use a spread operator ( ...) or the Object.assign() method const obj = { a:1, b:2 }; const add = { c:3, d:4, e: ['x','y','z'] }; let newObj = {...obj,...add};console.log(newObj); let newObj2 = Object.assign(obj,add);console.log(newObj);
    – Ztuons Ch
    Commented Jun 17, 2021 at 9:18
  • 1
    Yes, you are right, but in this specific case the idea was to avoid the creation of a new object. So, just modify the original one. Very useful when you have very large datasets and you don't want to create additional objects. Commented Jun 17, 2021 at 13:41
11

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

7
cart.push({"element":{ id: id, quantity: quantity }});
3
  • 4
    can't do cart.push because cart is an object now! :(
    – HypeZ
    Commented Jan 9, 2013 at 12:04
  • any specific reason why its is an object rather than array?
    – Cris
    Commented Jan 9, 2013 at 12:06
  • because i got it from "cart = JSON.parse(jsonfile)" and it gives an object
    – HypeZ
    Commented Jan 9, 2013 at 14:02
6

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

5
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.

3

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

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;
                    });
2
  • How do you add a value to that new JSON structure that you have created? Commented Dec 6, 2018 at 9:45
  • 1
    @JudeFernandes cart[key]=value basically its a key value map. Do upvote if the answer was helpful. Thanks!
    – Saad Patel
    Commented Dec 7, 2018 at 17:22
3

In ES9, you can add multiple elements to an object using object spread syntax, which has the benefit of avoiding repeated code:

let myObj = { 
  name: "John", 
  age: 30,
};

myObj = {
  ...myObj, // spread the original myObj elements
  city: "New York", 
  country: "USA",
};

console.log(myObj); // { name: "John", age: 30, city: "New York", country: "USA" }

In this example, we added two new properties city and country to the myObj object using object spread syntax.

2
 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';
1
  • While this is a way of achieving the same results, this solution is not neat.
    – warunapww
    Commented May 7, 2015 at 21:57
2

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

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.

2

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:

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

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

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

console.log(card);

1

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

1

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
1

Maybe everyone has taken this for granted:

const array = new Array("Saab", "Volvo");
const object_as_value = new Object({firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"});

function function_returns(){
    return "value 2"
}

var obj = {
    key1: array,
    key2: object_as_value,
    key3: function_returns()
}

console.log(obj)

Form a blog post:

ES6 computed property names feature allows you to assign an expression as the property name to an object within object literal notation. There is no need to create an object first.

You can also use template literals (string interpolation) as an expression for the computed property names:

const key = 'name';
const value = 'Atta';
> 
const user = {
    [key + '34']: value
};

console.log(user.name34); // Atta

Please also check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names

0

In case anyone else needs this, I finally found a good way to add objects or arrays of objects:

var myobj = {}

// These two options only work for single-valued keys, not arrays or objects
myobj["a"] = 1
myobj.b = 2

// This one works for everyting:
Object.assign(myobj, {"key": "value"});  // single-value

// Add object
Object.assign(myobj, {"subobj": 
  {
    "c": 3
  }
});

// Add array of objects
Object.assign(myobj, {"subarr": 
  [
    {
      "d": 4,
    },
    {
      "e": 5
    }
  ]
}); 
-2

var newObject = {element:{"id":10,"quantity":1}};

console.log(newObject);

1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jan 23, 2023 at 14:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.