Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new element to an existing object

I was looking for a way to add new elements to an an existing object like what push does with arrays

I have tried this and it didn't work :

var myFunction = {     Author: 'my name ',     date: '15-12-2012',     doSomething: function(){         alert("helloworld")     } }; myFunction.push({     bookName:'mybook',     bookdesc: 'new' }); console.log(myFunction); 
like image 316
Mina Gabriel Avatar asked Jun 15 '12 20:06

Mina Gabriel


People also ask

How do you add a new item to an object at a specific position?

If you want to insert an element at a given position, use the insert(pos, obj) method. It accepts one object and adds that object at the position pos of the list on which it is called.


1 Answers

Use this:

myFunction.bookName = 'mybook'; myFunction.bookdesc = 'new'; 

Or, if you are using jQuery:

$(myFunction).extend({     bookName:'mybook',     bookdesc: 'new' }); 

The push method is wrong because it belongs to the Array.prototype object.

To create a named object, try this:

var myObj = function(){     this.property = 'foo';     this.bar = function(){     } } myObj.prototype.objProp = true; var newObj = new myObj(); 
like image 61
Danilo Valente Avatar answered Oct 08 '22 18:10

Danilo Valente