2

I'm fairly new to javascript and I just started learning about objects & arrays. I have an object like this:

var myObj= {'1'{ID:'1',x:200,y:300},
              '2'{ID:'2',x:100,y:100}};

I'm willing to create another object inside the existing object("myObj") so that I can access it's properties using myObj['key'].x. Assume that I want to add the object {ID:'3',x:100,y:200} into myObj and access it's property values using myObj[3].x, myObj[3].y etc., I know that .push only works for arrays so I'm out of options.

Black Snow
  • 43
  • 7

2 Answers2

1

You can just use myObj[3] = {ID:'3',x:100,y:200}; to add the object.

Saravana
  • 37,852
  • 18
  • 100
  • 108
0

Try this:

function myFunc(id, x, y){
    var obj={};
    obj.ID = id.toString();
    obj.x = x;
    obj.y = y;
    return obj;
}
function myFunc2(id, x, y){
    myObj[id] = myFunc(id, x, y);
}

You can use myObj[3].xto get the "x" value from the object.

Edited: Call myFunc2 with desired parameters. e.g., myFunc2(3,100,200);

J.Jay
  • 249
  • 1
  • 4
  • 18
  • 2
    The implicit reference to `myObj` inside the function is a rather ugly construct; why don't you simply return the new object so that you can do `myObj[3] = myFunc(105, 100, 200);`? – Ja͢ck Jun 25 '15 at 02:48
  • 1
    Sorry. I'm new to javascript, too. Thanks for the advice :) – J.Jay Jun 25 '15 at 02:50