javascript - Object with another's object's property as a key -


i have object this: var myobj = {action1:0, action2:1, action3:2};

test function gets values list parameters , simplify unit-testing want human readable labels inside of function

function myfunc(someaction, anotheraction, blablabla) {     console.log("action: " + arguments[0] + " action: " + arguments[1]);     //some code here }   

so inside of function can see values 0 1 2

trying workaround tried create new object this

var dictobj = {myobj.action1:"action1", myobj.action2:"action2", myobj.action3:"action3"} 

and resolve values names inside of function:

console.log("action: " + dictobj[arguments[0]] + " action: " + dictobj[arguments[1]]); 

but didn't work because of

'uncaught syntaxerror: unexpected token .' 

how can rework code readable description?

in es5 , earlier, have create object series of statements:

var dictobj = {}; dictobj[myobj.action1] = "action1"; dictobj[myobj.action2] = "action2"; dictobj[myobj.action3] = "action3"; 

as of es2015 (aka "es6"), can computed property names in object initializer instead:

let dictobj = {     [myobj.action1]: "action1",     [myobj.action2]: "action2",     [myobj.action3]: "action3" }; 

you can use expression within [] create property name; in case it's simple property lookup.

in both cases, note there's no live relationship; if change myobj.action1 42 later, after doing above, doesn't have effect on property name in dictobj.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -