简体   繁体   中英

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:

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? is it even possible in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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