0

I tried a lot searching and didnt get desired solutions.

What I want to achieve is

var myObject {
  id1 : { 
    name:place_name,
    location : place_loc
  },
  id2 : { 
    name:place_name,
    location : place_loc
  },
  id3 : { 
    name:place_name,
    location : place_loc
  }
}

What I want to do is that Initially I want the properties "id1", "id2".. to be dynamic. And then dynamically assign name:place_name and other properties of each property.

I dont know the number of properties (id1,id2,id3...) hence would like to add them dynamically and following the addition of properties(id1,id2... ) I want to dynamically add the property values. (place_name & place_loc) of each id.

My code looks something like this.

var myObject = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber1].place = "SomeLoc1";
myObject[idnumber2].place = "SomePlace1";
myObject[idnumber2].place = "SomeLoc1";

But it gives error.

I know it seems simple doubt but any help would be grateful.

Thanks in advance. :)

3 Answers 3

1

You are trying to set a value of already assigned objects at keys "idnumber1", etc.

What you'll need is to initialize each objects for your ids like this:

var myObject = {};
myObject[idnumber1] = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber2] = {};
myObject[idnumber2].place = "SomeLoc1"
Sign up to request clarification or add additional context in comments.

1 Comment

Or better: myObject[idnumber1] = { place: "SomePlace1" }
0

I would do it this way, it's not exactly what you did ask for, but I think it will become easier to change this later on.

function Place(name, location) {
    this.name = name;
    this.location = location;
}

var myObject = {}
myObject['id1'] = new Place('Foo', 'Bar');
myObject['id2'] = new Place('Internet', 'test');
console.log(myObject);

Comments

0

To dynamically create objects in your collection, you can use a numerical counter variable to create your object collection (myObject["id" + i] = {name: place_name, location: place_loc}).

An example:

var myObject = {};
for (i = 0; i < 20; i++){
    myObject["id" + i] = {name: place_name, location: place_loc}
}

In practice, you can use a counter that you increment outside of a loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.