TronNatthakorn
TronNatthakorn

Reputation: 23

Access to PropertyName of object itself as string

I have object define like this

var obj = { abcdefghijkl: 'abcdefghijkl', other_key: 1234 };

Can I define object for get property name itself as string in Javascript ? Like this

var obj = { abcdefghijkl: getSelfPropertyName, other_key: 1234 };

I don't want for this.abcdefghijkl

Upvotes: 1

Views: 52

Answers (3)

Redu
Redu

Reputation: 26161

This is a problem that one can typically solve with variants of construction patterns. Lets use a classic approach.

function MyObject(...props){
  props.forEach((p,i) => this[p] = i ? "default value" : p);
}

var obj = new MyObject("abcdefghijkl", "other_prop", "yet_another_one");
console.log(obj);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386540

You could use an ES6 feature, Proxy

var obj = { abcdefghijkl: 'getSelfPropertyName', other_key: 1234 },
    p = new Proxy(obj, {
        get: function(target, prop) {
            return target[prop] === 'getSelfPropertyName' ? prop : target[prop];
        }
    });
   
console.log(p.abcdefghijkl); // 'abcdefghijkl'

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074038

Can I define object for get property name itself as string in Javascript?

No, there's no shortcut mechanism that lets you define a property with a value the same as the property name within an object initializer.

You can do it in a two-step:

var s = "abcdefghijkl";
var obj = {other_key: 1234};
obj[s] = s;
console.log(obj);

If you absolutely, positively have to do it in a single expression, you can use a temporary function, but it's not pretty:

var obj = (function(s) {
  var o = {other_key: 1234};
  o[s] = s;
  return o;
})("abcdefghijkl");
console.log(obj);

Upvotes: 3

Related Questions