Luke Vo
Luke Vo

Reputation: 20668

In Javascript is it possible to create an object with dynamic (undetermined) properties/members?

I try to achieve this in Javascript:

var a = new MyObj();
console.log(a.Foo()); // Print Foo
console.log(a["Bar"]()); // Print Bar

Basically, I don't know beforehand the property/member name that is needed, but depends on the calling I return it, a bit similar to C# ExpandoObject (dynamic).

Is it possible to make such an object in Javascript?

Note: I know it is possible to add the properties, however, in my case I do not know beforehand which are needed to add.

a.Foo = () => { return "Foo"; }

This is not possible because I don't know Foo will be needed.

Upvotes: 1

Views: 41

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

You could use a Proxy and implement only a getters by returning a function which is a closure over the key.

var a = new Proxy({ baz: 42 }, {
        get: function (target, prop, receiver) {
            return prop in target
                ? () => target[prop]
                : () => prop;
        }
    });

console.log(a.Foo());    // Foo
console.log(a["Bar"]()); // Bar
console.log(a.baz());    // 42

Upvotes: 3

ZER0
ZER0

Reputation: 25322

In modern browsers you can achieve that using Proxy:

Here an example to achieve what you described:

const o = new Proxy({}, {
  get(obj, name) {
    return () => name
  }
});

In the specific case you don't have an original object you want to "proxy", but you probably want to read more on the link above for adding all the traps you want to.

Upvotes: -2

Akhil Aravind
Akhil Aravind

Reputation: 6130

Sorry, i made a mistake, take a look at the snippet now; hope this is what you are looking into.

can you check the snippet now .:D

let a = {}; // object
a.Foo = ()=> {return 'foo'};
a.Bar = ()=> {return 'bar'};

a.address = {}; // object inside object
a.address.houseno = '122';

console.log(a.Foo()); // Print Foo
console.log(a["Bar"]()); // Print Bar
console.log(a.address.houseno)

Upvotes: 0

Related Questions