简体   繁体   中英

Refer to key in value when creating object in javascript

Is there any syntax to do something like the following

var obj = {a: this, b: this}

and get

obj = {a: 'a', b: 'b'}

You can do this:

var obj = {a: "this is A", b: "this is B"}
obj.a equals to "this is A"
obj.b equals to "this is B"

A quick snippet using this object example to add the pointer locations stored in an object:

 function getMousePosition(event){ var mouse = {x: 0, y: 0}; mouse.x = event.clientX; mouse.y = event.clientY; Elem = document.getElementById("Elem"); Elem.innerHTML = "Simple Mouse Position by Khriztian Azuaje.<br><br>" + "X pos: " + mouse.x + ", Y pos: " + mouse.y; } 
 #Elem { background:black; text-align: center; color:white; padding:2px; display: flex; align-items: center; justify-content: center; height:160px; } 
 <body onmousemove="getMousePosition(event)"> <div id="Elem"></div> </body> 

If you want to create an object that has a bunch of keys and values equaling the same string, it's as simple as:

var obj = {};
['a','b'].forEach(function(item) {
    obj[item] = item;
});

Yes! I'm not sure why you would use but here it is:

var obj = { a: 'you', b: 'they'};
var newObj = {};

for (var key in obj) { 
    newObj[key] = key
};

//newObj = {a: "a", b: "b"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM