1

Is there any syntax to do something like the following

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

and get

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

3 Answers 3

1

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;
});
Sign up to request clarification or add additional context in comments.

4 Comments

I like this solution, even though I was wondering if it was possible on object creation
By the way, in node, where I'm using this, you need to initialize the array before using forEach.
@ykay - Are you sure? I just tried typing ['a','b','c'].forEach(function(c) { Console.log(c); }); into node.js. It worked.
Hi Andrew, you're right, express was throwing an error if I started a line with the array but the line before wasn't closed with a semicolon
1

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"}

1 Comment

Thanks, this seems pretty good, but I was wondering if I could do this on the object creation
1

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>

4 Comments

It might help to explain a bit about why your code works.
Why would you go to the trouble of initializing obj to {a: this, b: this}? Writing var obj = {} would give you identical results in the end
@SuperBiasdMan He asked for a syntax, not how objects work. I rest assured giving a simple object syntax without explanation knowing its what he's after (in a simple way).
I'll edit my answer to avoid unnecessary missunderstandings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.