Help with basic variable and object output

Hello! Long time reader, first time poster.
Admittedly I’m a total novice at javascript and I’ve been going crazy for a week trying to figure this out.

I have these values

<div id="productID">Text1</div>
<div id="productNAME">Text2</div>

and this code

var prodID = document.getElementById("productID").textContent;
var prodNAME = document.getElementById("productNAME").textContent;
var products = {prodID : prodName};

When I check the console for the variable products I get

{productID: “Text2”}

What I need it to output is

{ ‘Text1’ : ‘Text2’ }

I know the problem has to be in how I’m calling the variable products and I’ve read that I probably need to set an object first? I can’t for the life of me figure this out.

I’m at the end of my rope here. Like I mentioned, I’m very new at JS - please don’t throw stones.

The problem is that property names in object literals cannot be variables.

What you need is add the property after you created the object.

var products = {};
products[var1] = var2;

Mind that–depending on what you want to do afterwards–an array might be the more sensible solution.

var products = [];
products.push({
    id: prodID,
    name: prodNAME
});
2 Likes

Well actually, since 2015 (cough) we have computed property names with an analogous syntax… ;-)

var products = { 
  [prodID]: prodName 
}
3 Likes

This did the trick! Thank you so much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.