Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push an object in an Array?

Iam trying to push in array an object, but I get always error.

fCElements = [],
obj = {};

obj.fun = myFunction;
obj.id = 2;

fCElements.push ({

   obj,
   myid:2,
   name:'klaus'     

})

how I can push into array functions like "myFunction"?

Thanks

like image 339
user3485065 Avatar asked Dec 12 '25 23:12

user3485065


1 Answers

In the Object literal, you can only give key-value pairs. Your obj doesn't have any value.

Instead, you can do like this

var fCElements = [];
fCElements.push({
    obj: {
        fun: myFunction,
        id: 2
    },
    myid: 2,
    name: 'klaus'
});

Now, you are creating a new object, obj, on the fly, while pushing to the array. Now, your fCElements look like this

[ { obj: { fun: [Function], id: 2 }, myid: 2, name: 'klaus' } ]
like image 174
thefourtheye Avatar answered Dec 15 '25 12:12

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!