0

Is there a way I can get a property`s name inside the property itself?

I mean something like this:

let myObj = {
    myProperty: {
        name: <propertyName>.toString()
    }
};

console.log(myObj.myProperty.name); // Prints `myProperty`
Lucas Araujo
  • 453
  • 4
  • 14

1 Answers1

1

No, there isn't. There's nothing available when the object initializer is evaluated that provides that information.

Presumably if this were a one-off, you'd just repeat the name. If it's not a one-off, you could give yourself a utility function to do it:

// Define it once...
const addProp = (obj, name, value = {}) => {
    obj[name] = value;
    value.name = name;
    return obj;
};

// Then using it...
let myObj = {};
addProp(myObj, "myProperty");
addProp(myObj, "myOtherProperty", {foo: "bar"});

console.log(myObj.myProperty.name);
console.log(myObj.myOtherProperty.name);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875