0

Lets say I have a object

obj1 : {
  "a" : 22
  "b" : 33
  "c" : 67
}

and obj2 as

obj2 : {
  x:"obj1.a" (string - path)
  y: "obj1.b" (string- path)
}

but when i do obj2.x I get obj1.a which is correct but I want 22, How do I do this? Or is there any npm package which takes care of this?

danh
  • 62,181
  • 10
  • 95
  • 136

1 Answers1

0

Ok, so you can use get logic when defining your object in order to achieve this.. basically get would call a function when the key is accessed and the value would be what that function returns

let obj1={
  "a" : 22,
  "b" : 33,
  "c" : 67
}

let obj2={
  get x(){
    return obj1.a
  },
  get y(){
    return obj1.b
  }
}

console.log([obj2.x,obj2.y]) //[22,33]
obj1.a++; obj1.b++ //changing obj1 to prove that it obj2 will change when obj 1 changes
console.log([obj2.x,obj2.y]) //[23,34]
The Bomb Squad
  • 4,192
  • 1
  • 9
  • 17