Javascript object: property name backlink

I am trying to make it easier to create the contents of a javascript object so that the values ​​depend on the names of the participants, 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 it possible for a reference to a member name to be defined in the value definition using something like the intended function myName () ?

If no native method exists, then what is the recommended way to accomplish this?

You may ask, "Why does this guy need this weird way of generating objects?" , and the answer is this: in my code, the names of the participants / fields can change, the default values ​​will be copied with the only difference being the link to the name of the participant, and I don’t want to define the numeric values ​​in each key-value pair twice, so I’m going back call back the name inside the value definition.

+4
source share
2 answers

Are you looking for the ES6 feature, Proxy

An object is Proxyused to define user behavior for basic operations (for example, searching for properties, assigning, listing, calling a function, etc.).

prop {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!
Hide result
+1

, , - .

. , , , . :

var obj = {
    1: function(key){return "you selected 1";},
    2: function(key){return "wow, you selected 2";},
    3: function(key){return "this time, you selected " + key;},
    137: function(key){return "I think you've chosen " + key + " this time.";},
    513: function(key){return key + " is the answer!";}
};

function getValue(key) {
    return obj[key](key);
}

, :

var value = getValue(137);

, OP () .

0

Source: https://habr.com/ru/post/1664714/


All Articles