I have an object as follows:
var obj = {
parentKey : {
nestedKey1 : value,
nestedKey2 : function () {
return parentKey + nestedKey2;
}
}
};
Is there a way to use the values within the actual name of the parentKey
and nestedKey1
and/or nestedKey2
in a function held in one of the nested key-value pairs as the one above?
In my actual scenario the keys
are all numerical values I wish to use as criteria for a for loop
.
Updated Scenario To Question
As an exercise to learn JavaScript I decided to code the logic of an elevator system. To do this I have made an object which represents the building and this object contains each floor, nested within each floor are the data of the number of people wishing to travel to another floor as follows:
var floorData = {
<floor number> : {
<people going to floor X> : <number of people>,
<people going to floor Y> : <number of people>,
peopleGoingUp : <formula that sums amount of people going up>,
peopleGoingDown : <formula that sums amount of people going down>
}
};
I want to include within each <floor number>
object a property that sums the amount of peopleGoingUp
and peopleGoingDown
by means of a formula. For this formula to work as I intend I need to access the <floor number>
name which is a numeric value from within the peopleGoingUp
and peopleGoingDown
formulas.
Here is my working example thus far and I have included peopleGoingUp
and peopleGoingDown
formulas in floor theBuilding[2]
. What I wish for is to change the hand entered value of theParentKey
to equal the name of the parent object.
// Total number of floors in building global object
var totalFloors = 3;
// Building object including amount of people waiting to take lift to other floors on each level of the building
var theBuilding = {
0 : {
1 : 2,
2 : 0,
3 : 1,
},
1 : {
0 : 1,
2 : 3,
3 : 2,
},
2: {
0 : 2,
1 : 1,
3 : 4,
goingUp : function () {
var sum = 0;
var theParentKey = 2; // this is supposed to be a direct reference to the parent object name to this nested object and thus equal to 2
for (i = 0; i <= totalFloors; i++) { // loop for total floors
if (i !== theParentKey && i >= theParentKey) {//sum if i isn't = this floor number and that i is greater than this floor number
sum += this[i]
}
};
return sum;
},
goingDown : function () {
var sum = 0;
var theParentKey = 2; // this is supposed to be a direct reference to the parent object name to this nested object and thus equal to 2
for (i = 0; i <= totalFloors; i++) { // loop for total floors from lowest
if (i !== theParentKey && i <= theParentKey) { //sum if i isn't = this floor number and that i is less than this floor number
sum += this[i]
}
};
return sum;
},
3 : {
0 : 0,
1 : 1,
2 : 4
}
};
console.log(theBuilding[2].goingUp()); // 4
console.log(theBuilding[2].goingDown()); // 3