0

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
Fiztban
  • 283
  • 2
  • 9
  • 22
  • yes, it can. Objects can reference anything, in any field. – abc123 Oct 23 '16 at 15:48
  • Great, how do I do that exactly ? I know that by using this.nestedKey1 I can access the value of nestedKey1 but how to I access the name of nestedKey1 – Fiztban Oct 23 '16 at 16:00
  • 2
    please add your scenario to the question. – Nina Scholz Oct 23 '16 at 16:02
  • `nestedKey2 : function () { return parentKey + nestedKey2; }` circular reference with `nestedey2`. – Nina Scholz Oct 23 '16 at 16:24
  • 2
    What do you want to reference? The property name? The property value? – Oriol Oct 23 '16 at 17:50
  • @NinaScholz I will add a scenario as I did effectively do a poor job at describing my question. Apologies, I am new to JavaScript and the lingo. Upcoming scenario. – Fiztban Oct 23 '16 at 21:08
  • @Oriol I want to use the property name `parentKey` within the `nestedKey2` function. Upcoming expanded scenario of what I am trying to achieve. Apologies for unclear question thus far. – Fiztban Oct 23 '16 at 21:09
  • 1
    Yeah, I don't think it's possible what you are trying to accomplish [without changing your data structure](http://stackoverflow.com/questions/1789892/access-parent-object-in-javascript). JavaScript doesn't have upward relationships. – Mikey Oct 23 '16 at 22:27
  • I thought that might be the case. I see the reference you have mentioned may hold promise to try a different approach. Thank you for your contribution! – Fiztban Oct 23 '16 at 22:30

3 Answers3

2

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?

You can do it in two ways.

Using lexical scope

The function inside nestedKey2 has access to the global scope. You can therefore reach every property inside obj using .:

obj.Parentkey

Using this

This is a bit more tricky as this inside a function in a multilevel object will point to the "same level" of the object as the function resides in. You can use this together with . to reach the lower levels of the object but there is no way to reach the higher levels.

You can, however, use a workaround implementing a circular reference:

var myObj = {

    levelAccess: function() {
        this.two.__ = this;
        return this;
        },

    one: 'one',
    two: 
        {
        __: [],

        myFunction: function () {return this.__.one}
        }

    }.levelAccess();

This solution requires that you add a __ property for each level that needs access to a higher level and then initialises all the __ properties via the levelAccess function. The solution should not cause any memory leaks, see this.

Community
  • 1
  • 1
rabbitco
  • 2,790
  • 3
  • 16
  • 38
1

If I understood your question, you want to get names of the keys. You can use Object.keys() while passing the current object this.

var obj = {
    parentKey : {
        nestedKey1: 3, 
        nestedKey2: function () {
            return Object.keys(this);
        }
    }
};

console.log(obj.parentKey.nestedKey2()); // ['nestedKey1', 'nestedKey2']
Mikey
  • 6,728
  • 4
  • 22
  • 45
  • 1
    Thank you for your contribution, being new I certainly didn't know of the `Object.keys()` as a new way of doing `Object.getOwnPropertyNames(this)`. However this doesn't give me access to the `parenKey` from within the `nestedKey2`. – Fiztban Oct 23 '16 at 21:07
1

See this is an example

var obj = {
    parentKey : {
        nestedKey1 : "value", 
        nestedKey2 : function () {
            var c = obj.parentKey;
            //console.log("we get "+ c.nestedKey1 +" & "+ c.nestedKey3);
            //you can update values
            //obj.parentKey.nestedKey1 = "new value";
            console.log("we get "+ c.nestedKey1 +" & "+ c.nestedKey3);
            return "we get "+ c.nestedKey1 +" & "+ c.nestedKey3;
        },
        nestedKey3 : "another value" 
    }
};

obj.parentKey.nestedKey2();
var an = window["obj"]["parentKey"]["nestedKey3"];
console.log(an);
Mamdouh Saeed
  • 2,302
  • 1
  • 9
  • 11
  • Hello and thank you for your contribution. This seems to me (I am fairly new to this) a good way to reference objects within the nested object using a reference for them that includes the parentKey but I am not actually using the name of the parentKey. I believe it was an error in my explanation of the question. Please see the updated one coming up shortly. – Fiztban Oct 23 '16 at 21:04