I am trying to ease the creation of the content of a javascript object so that values depend on member names, something like this:
var obj = {
1: "you selected 1",
2: "wow, you selected 2",
3: "this time, you selected " + myName(), //myName() gets resolved to 3
137: "I think you've chosen " + myName() + " this time.", //myName() gets resolved to 137
513: myName() + " is the answer!" //myName() gets resolved to 513
};
Is that possible to backreference the member name in the definition of the value, using somethink like the supposed function myName()?
If no native method exists, what is the recommended way to accomplish this?
You may ask "Why does this guy need this stange way of generating objects??", and the answer is: in my code, member/field names may change, default values will be copied with the only difference being the reference to the member name, and I don't want to define number values in each key-value pair twice, hence I am after a way of backreferencing the name inside the value definition.
You are looking for an ES6 feature, Proxy
The
Proxy
object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
Then take the prop
with the actual key and replace the placeholder {key}
with the actual key.
var obj = {
1: "you selected {key}",
2: "wow, you selected {key}",
3: "this time, you selected {key}",
137: "I think you've chosen {key} this time.",
513: "{key} is the answer!"
},
p = new Proxy(obj, {
get: function(target, prop) {
return target[prop] && target[prop].replace("{key}", prop);
}
});
console.log(p[3]); // this time, you selected 3
console.log(p[137]); // I think you've chosen 137 this time.
console.log(p[513]); // 513 is the answer!
obj.foo = 'This is {key}!'; // create new property foo
console.log(p.foo); // This is foo!
obj.bar = obj.foo; // assign foo to bar
delete obj.foo; // delete foo
console.log(p.foo); // undefined
console.log(p.bar); // This is bar!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With