Reputation: 380
So I have two different set of objects:
var house = {};
house["01"] = {hID: "01", neighbh: "00001", name: "house 1"};
house["02"] = {hID: "02", neighbh: "00001", name: "house 2"};
house["03"] = {hID: "03", neighbh: "00002", name: "house 3"};
house["04"] = {hID: "04", neighbh: "00003", name: "house 4"};
var neighborhood = {};
neighborhood["00001"] = {id: "00001", name: "first neighborhood", houses: {} };
neighborhood["00002"] = {id: "00002", name: "second neighborhood", houses: {} };
neighborhood["00003"] = {id: "00003", name: "third neighborhood", houses: {} };
I want to be able to reference the house objects inside houses {} within neighborhood. But filter them to their respective neighborhood. i.e. house["01"] should go in the neighborhood["00001"] (those that have the neighborhood id matching house neighbh). This is so that I can have all the houses in one different object, but still be able to make changes to them through the neighborhood object. Hopefully I have managed to make myself clear.
Any help will be appreciated. Thanks
Upvotes: 0
Views: 993
Reputation: 707456
Objects in Javascript are passed and stored by reference. So, suppose you had a master array of all the houses:
var houses = [
{hID: "01", neighbh: "00001", name: "house 1"},
{hID: "02", neighbh: "00001", name: "house 2"}
];
And, you then had an array of neighborhood objects that each had some identifying information about the neighborhood and then a list of houses that are in that neighborhood:
var neighborhoods = [
{id: "00001", name: "first neighborhood", houses: [houses[0], houses[1]]}
];
In a structure like this, there is only one copy of each house object. You can modified it via any of the references you have. So, you can modified it via the master houses array. Or, you can modified it via the houses array inside the neighborhood. Each points to the exact same house object. So, when you modify it in one place, you are modifying the actual house object and everyone who has a reference to that particular house object will see those modifications.
So, in the structure you postured (which uses objects as containers instead of the arrays I used to hold multiple items). I think you can fill that out like this and accomplish what you're asking for:
var house = {};
house["01"] = {hID: "01", neighbh: "00001", name: "house 1"};
house["02"] = {hID: "02", neighbh: "00001", name: "house 2"};
house["03"] = {hID: "03", neighbh: "00002", name: "house 3"};
house["04"] = {hID: "04", neighbh: "00003", name: "house 4"};
var neighborhood = {};
neighborhood["00001"] = {id: "00001", name: "first neighborhood", houses: [house["01"], house["02"]]};
neighborhood["00002"] = {id: "00002", name: "second neighborhood", houses: [house["03"]] };
neighborhood["00003"] = {id: "00003", name: "third neighborhood", houses: [house["04"]] };
FYI, it seems like the list of houses in a neighborhood should be an array, not an object.
Upvotes: 1