简体   繁体   English

JavaScript - 获取嵌套属性的父对象

[英]JavaScript - Get nested property's parent object

let's say I have a nested object like this:假设我有一个这样的嵌套对象:

let object = {
  another : {
    yet_another : {
      last_one : {
      some_property : [1,2,3]
      }
    }
  } 
}

I can access some_property like this:我可以像这样访问some_property

object.another.yet_another.last_one.some_property;

And let's say I'm referring to this object in a variable:假设我指的是变量中的这个对象:

var x = object.another.yet_another.last_one.some_property;

How can I tell what's the parent object of some_property if I only have access the x variable?如果我只能访问x变量,我怎么知道some_property的父对象是什么? is it even possible in JavaScript?在 JavaScript 中甚至可能吗?

No, it's not possible.不,这不可能。 An object doesn't have a "parent" per se.对象本身没有“父对象”。 Observe:观察:

let object = {
  another : {
    yet_another : {
      last_one : {
        some_property : [1,2,3]
      }
    }
  } 
};

let another_object = {
  foo: object.another.yet_another.last_one.some_property
};

Now what?怎么办? The array is now equally a member of both objects.该数组现在同样是两个对象的成员。

No, because when doing the following line;不,因为在执行以下行时;

var x = object.another.yet_another.last_one.some_property;

then you assign x to the value of some_property , nothing more.然后将x分配给some_property的值, some_property而已。

Based on your comment to an answer, the solution to your (actual) problem should be don't move objects around.根据您对答案的评论,您的(实际)问题的解决方案应该是不要移动物体。 Mutability can be very very expensive (eventually prohibitively) when it comes to maintaining an application.在维护应用程序时,可变性可能非常昂贵(最终令人望而却步)。

Just create new objects:只需创建新对象:


const firstObject = {
   prop1: 'some value',
   prop2: {
      prop3: 'some value',
      prop4: [1,2,3,4]
   }
}

// don't do
const secondObject = { }
secondObject.prop2.prop4 = firstObject.prop2.prop4

// instead do
const secondObject = { ... }
const newObject = {
  ...secondObject,
  prop2: {
   ...secondObject.prop2,
   prop4: firstObject.prop2.prop4
  }
}

You may want to look into immutablejs.您可能想研究一下 immutablejs。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM