Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an element into a existing array in javascript/jquery

I have an array in javascript

var myArr = {
    'textId':'123', 
    'type':'animal', 
    'content':'hi dog', 
    'expires':'27/10/2012' 
};

$.each(myArr, function(myArrArrKey, myArrArrValue){
    console.log( myArrArrValue );
});

The above console prints following values

123
app
hi app
27/10/2012

Now i am want to append an element to the existing array, i am trying to do like the below one

myArrValue.push({'status':'active'});

The above push throws following error

TypeError: Object #<Object> has no method 'push'

Kindly help me how to append to that existing array element.
I want to print the array like

123
app
hi app
27/10/2012
active
like image 601
krrr25 Avatar asked Jul 15 '26 01:07

krrr25


2 Answers

Just do this.

myArr.status = 'active'

or

myArr["status"] = 'active'

Your myArr is an Object not an Array..

push function is available to an Array variable.

like image 186
Yograj Gupta Avatar answered Jul 17 '26 13:07

Yograj Gupta


this isn't an array, it's an object!

var myArr = {
    'textId':'123', 
    'type':'animal', 
    'content':'hi dog', 
    'expires':'27/10/2012' 
};

this isn't necessary with jQuery

$.each(myArr, function(myArrArrKey, myArrArrValue){
    console.log( myArrArrValue );
});


easier would be

for ( var k in myArr ) {
    console.log( myArr[ k ];
}


to add new entries to your "array"

myArr[ 'foo' ] = 'bar';  // this is array notation

or

myArr.foo = 'bar';  // this is object notation


to remove entries from your "array"

delete myArr[ 'foo' ];

or

delete myArr.foo;


FYI: myArrValue.push({'status':'active'}); wont work. myArrValue isn't the "array" itself and also not an array having the method push. If it would be an array the result would be, that your latest entry is the whole an object {'status':'active'}

like image 44
bukart Avatar answered Jul 17 '26 13:07

bukart



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!