1

If I have the following object:

const obj = {
  nestedObj: {
    foo: "bar",
  }
}

and access one of the nested objects using obj.nestedObjA, will the resulting object contain some information of its key in the original object, or will it simply be the object literal { foo: "bar" }?

I would like to achieve something like this:

const fun = (nestedObj) => {
  console.log(nestedObj.key); // print the key of obj in its parent object
  console.log(nestedObj.foo);
}

without actually storing the key twice, e.g.:

const obj = {
  nestedObjA: {
    key: "nestedObjA", // I want to remove this line
    foo: "bar",
  }
}

fun(obj.nestedObjA);
Toivo Säwén
  • 1,905
  • 2
  • 17
  • 33
  • Did you check `getter` in javascript objects https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get ? – Ahmed Kesha Mar 11 '20 at 10:51

2 Answers2

0

You could use a proxy to define a getter. When the getter triggers, you can check to see if the key is in your object, and if it is, return a new object which has the key as a property along with the object contents like so:

const obj = {
  nestedObj: {
    foo: "bar",
  }
};

const new_obj = new Proxy(obj, {
  get: (obj, key) => {
    if(key in obj) {
      return {
        key,
        ...obj[key]
      };
    }
  }
});

const fun = (obj) => {
  console.log(obj.nestedObj); // print the key of obj in its parent object
  console.log(obj.foo);
}

fun(new_obj);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 1
    Note that this risks clashing with existing properties of the object. I'd think the more useful way would be to simply explicitly pass the key as data to the function, e.g. `fun('nestedObj', obj.nestedObj)`. If that feels too repetitive, you could make a helper function like `f(fun, obj, 'nestedObj')`… – deceze Mar 11 '20 at 11:14
  • @deceze thanks for pointing that out. I like the idea of using the helper function – Nick Parsons Mar 11 '20 at 11:18
-1

You can try to do :

Object.keys(obj) // this will print the keys of the current object

cf: Object Keys

André Gomes
  • 142
  • 1
  • 6