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
-
That is an object, not an array. More importantly, your output does not seem to match your input in the first case.user1726343– user17263432012年10月27日 11:17:44 +00:00Commented Oct 27, 2012 at 11:17
-
this is a json object not an arrayOmu– Omu2012年10月27日 11:18:15 +00:00Commented Oct 27, 2012 at 11:18
7 Answers 7
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.
Comments
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'}
Comments
The answer is in the error... you have an object, not an array. Use object notation
myArr.status='active'
Comments
Simply use:
myArrValue.status = 'active';
but be aware that what you are using is an object, not an array. Another way to add properties to an object is:
object[key] = value;
Comments
this a json object not array push would for an array for json you do
myObj.NewProp = 123;
Comments
Just for the kicks of it..
function push( obj ) {
var prop;
for ( prop in obj ) {
this[prop] = obj[prop];
}
return this;
}
Your object, remember to assing the push method.
var obj = {
a: "a",
b: "b",
push: push
};
And the push:
obj.push({
c: "c",
d: "d"
});
Comments
myArr["status"] = 'active';
or
myArr.status ='active';