【问题标题】:JavaScript: Can a nested object value reference its parent object key?JavaScript:嵌套对象值可以引用其父对象键吗?
【发布时间】:2017-03-05 10:07:39
【问题描述】:

我有一个对象如下:

var obj = {
    parentKey : {
        nestedKey1 : value, 
        nestedKey2 : function () {
            return parentKey + nestedKey2;
        }
    }
};

有没有办法在上述嵌套键值对之一中保存的函数中使用 parentKeynestedKey1 和/或 nestedKey2 的实际名称中的值?

在我的实际场景中,keys 都是我希望用作for loop 标准的数值。


更新场景到问题

作为学习 JavaScript 的练习,我决定编写电梯系统的逻辑代码。为此,我制作了一个代表建筑物的对象,该对象包含每一层,嵌套在每一层中的是希望前往另一层的人数数据,如下所示:

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>
    }
};

我想在每个 &lt;floor number&gt; 对象中包含一个属性,该属性通过公式将 peopleGoingUppeopleGoingDown 的数量相加。要让这个公式按我的意图工作,我需要访问 &lt;floor number&gt; 名称,它是来自 peopleGoingUppeopleGoingDown 公式中的数值。

到目前为止,这是我的工作示例,我在楼 theBuilding[2] 中包含了 peopleGoingUppeopleGoingDown 公式。我希望将theParentKey 的手动输入值更改为等于父对象的名称。

// 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

【问题讨论】:

  • 是的,可以。对象可以引用任何字段中的任何内容。
  • 太好了,我该怎么做呢?我知道通过使用 this.nestedKey1 我可以访问 nestedKey1 的值,但是如何访问 nestedKey1 的名称
  • 请将您的场景添加到问题中。
  • 你想参考什么?物业名称?属性值?
  • 是的,我认为您尝试完成的事情不可能without changing your data structure。 JavaScript 没有向上的关系。

标签: javascript object nested parent


【解决方案1】:

如果我理解您的问题,您想获取键的名称。您可以在传递当前对象this 时使用Object.keys()

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

console.log(obj.parentKey.nestedKey2()); // ['nestedKey1', 'nestedKey2']

【讨论】:

  • 感谢您的贡献,作为新人,我当然不知道Object.keys() 是一种新的Object.getOwnPropertyNames(this) 方式。但是,这并不能让我从nestedKey2 中访问parenKey
【解决方案2】:

这是一个例子

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);

【讨论】:

  • 您好,感谢您的贡献。在我看来(我对此相当陌生)使用包含 parentKey 的引用来引用嵌套对象中的对象的好方法,但我实际上并没有使用 parentKey 的名称。我认为这是我对问题的解释有误。请查看即将发布的更新版本。
【解决方案3】:

有没有办法使用实际名称中的值 parentKey 和 nestedKey1 和/或 nestedKey2 在一个函数中 嵌套的键值对和上面那个一样吗?

你可以通过两种方式做到这一点。

使用词法作用域

nestedKey2 中的函数可以访问全局范围。因此,您可以使用. 访问obj 内的每个属性:

obj.Parentkey

使用this

这有点棘手,因为多级对象中的函数内部的this 将指向函数所在对象的“同一级别”。您可以将this. 一起使用以达到对象的较低级别,但无法到达较高级别。

但是,您可以使用实现circular reference 的解决方法:

var myObj = {

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

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

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

    }.levelAccess();

此解决方案要求您为需要访问更高级别的每个级别添加一个__ 属性,然后通过levelAccess 函数初始化所有__ 属性。该解决方案不应导致任何内存泄漏,请参阅this

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2021-08-17
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2020-03-20
    • 2019-03-02
    • 2014-02-20
    • 1970-01-01
    相关资源
    最近更新 更多