0

I have an object in a variable var o={}; I want to do something like what .push() method doing in array for my object.

JS code:

// Array:
var ar=[];
ar.push('omid');
ar.push('F');
var got=ar[1];
// above code is standard but not what I'm looking for !
/*-------------------------------------*/


// Object:
var obj={};

/*  obj.push('key','value'); // I want do something like this
    var got2=obj.getVal('key'); // And this
*/

Is this possible at all ?

Pejman
  • 2,442
  • 4
  • 34
  • 62
  • possible duplicate of [How can I add a key/value pair to a JavaScript object literal?](http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object-literal) – Felix Kling Aug 31 '13 at 15:43

3 Answers3

4
var obj = {}

// use this if you are hardcoding the key names
obj.key = 'value'
obj.key // => 'value'

// use this if you have strings with the key names in them
obj['key2'] = 'value'
obj['key2'] // => 'value'

// also use the second method if you have keys with odd names
obj.! = 'value' // => SyntaxError
obj['!'] = 'value' // => OK
tckmn
  • 57,719
  • 27
  • 114
  • 156
3

Since Object-Literals use a Key->Value model, there is no JS method to "push" a value.

You can either use Dot Notation:

var Obj = {};

Obj.foo = "bar";

console.log(Obj);

Or Bracket Notation:

var Obj = {},
    foo = "foo";

Obj[foo]   = "bar";
Obj["bar"] = "foo";

console.log(Obj);

Consider reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, as arming yourself with this knowledge will be invaluable in the future.

honyovk
  • 2,717
  • 18
  • 26
2

Here is some javascript magic that makes it work. Take a look.

var obj = {};
Object.defineProperty(obj,'push',{
 value:function(x,y){
  this[x]=y;
 }
});

obj.push('name','whattttt');  <<<this works!!!

obj;
//{name:'whattttt'}
obj.name or obj['name']..
//whattttt

The reason i defined .push function using Object.defineProperty because i didn't want it to show up as a property of object. So if you have 3 items in object this would have always been the 4th one. And mess up the loops always. However, using this method. You can make properties hidden but accessible.

Though i don't know why you would use this method when there is already a easy way to do it.

to assign a value do this

obj.variable = 'value';

if value key is number or weird do this...

obj[1] = 'yes';

to access number or weird name you also do that

obj[1];

and finally to assign random keys or key that has been generated in code, not hard coded, than use this form too.

var person= 'him';

obj[him]='hello';
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168