I know there is already an accepted answer for this but I thought I'd document my idea somewhere. Please [people] feel free to poke holes in this idea, as I'm not sure if it is the best solution... but I just put this together a few minutes ago:
Since, the prototype function is returning this you can continue to chain .push's to the end of your obj variable: obj.push(...).push(...).push(...);
Another feature is that you can pass an array or another object as the value in the push function arguments. See my fiddle for a working example: http://jsfiddle.net/7tEme/
Your example shows an Object, not an Array. In that case, the preferred way to add a field to an Object is to just assign to it, like so:
You can create a class with the answer of @Ionuț G. Stan
Creating a new object with the last class:
Printing the object
Printing a Key
I'm newbie in javascript, comments are welcome. Works for me.
because your arr is not really an array... It's a prototype object. The real array would be:
but it's still not right. It should actually be:
Either
obj['key3'] = value3
orobj.key3 = value3
will add the new pair to theobj
.However, I know jQuery was not mentioned, but if you're using it, you can add the object through
$.extend(obj,{key3: 'value3'})
. E.g.:jQuery.extend(target[,object1][,objectN]) merges the contents of two or more objects together into the first object.
And it also allows recursive adds/modifications with
$.extend(true,object1,object2);
:You can either add it this way:
or this way:
The answers suggesting keying into the object with the variable
key3
would only work if the value ofkey3
was'key3'
.I know there is already an accepted answer for this but I thought I'd document my idea somewhere. Please [people] feel free to poke holes in this idea, as I'm not sure if it is the best solution... but I just put this together a few minutes ago:
You would utilize it in this way:
Since, the prototype function is returning
this
you can continue to chain.push
's to the end of yourobj
variable:obj.push(...).push(...).push(...);
Another feature is that you can pass an array or another object as the value in the push function arguments. See my fiddle for a working example: http://jsfiddle.net/7tEme/