Dynamic Object Reference in Object.keys(obj) [duplicate]

475
February 13, 2020, at 03:40 AM
This question already has answers here:
“Variable” variables in Javascript? (7 answers)
Closed 4 hours ago.

How can I iterate through an Object.Keys(obj) where the obj might change (and thus need to be a variable that changes)?

const modelBasicSKUs = { 
device: { 
    "black": "12", 
    "platinum": "23" 
  }, 
  keyboard: { 
    "black":"12", 
    "blue":"23", 
    "red":"34", 
    "platinum":"45" 
  }, 
  pen: { 
    "black":"12", 
    "platinum":"44", 
    "burgundy":"56", 
    "blue":"45" 
  } 
}; 
 
(async () => { 
let selectedDevice = "modelBasic"; 
 
document.querySelector('#testel').innerHTML = tmpl; 
 const tmpl = ` 
  ${Object.keys(selectedDevice + 'SKUs').map(key => ( 
    `<div>${key}</div>` 
  )).join("")} 
`; 
 
  })();
<div id="testel"></div>

I believe the important part lies in

${Object.keys(selectedDevice + 'SKUs').map(key => (

Do I need another template literal to be able to point to the other objects when selectedDevice changes? I am guessing that [selectedDevice + 'SKUs] expression returns a string and thus Object.keys does not detect an object out of a string?

Answer 1

If you can wrap the objects inside another object, you can access the objects as string keys from the container object. For instance if you make modelBasicSKUs a global object, you will be able to access it as window['modelBasicSKUs'] or this['modelBasicSKUs ']:

modelBasicSKUs = { 
device: { 
    "black": "12", 
    "platinum": "23" 
  }, 
  keyboard: { 
    "black":"12", 
    "blue":"23", 
    "red":"34", 
    "platinum":"45" 
  }, 
  pen: { 
    "black":"12", 
    "platinum":"44", 
    "burgundy":"56", 
    "blue":"45" 
  } 
}; 
 
let endName = 'SKUs'; 
console.log(Object.keys(this['modelBasic' + endName]));

  • Instagram followers without drop
READ ALSO
Accessing A Block By Clicking A Button

Accessing A Block By Clicking A Button

I have a form in my webpage and I have created a button in the footer area of my pageI wants if anyone clicks this button then they will go to the contact form which is located on the top of my page

476
Altering element&#39;s content in javascript

Altering element's content in javascript

which is advisableto use?setContent or

437
How to completely stop/reset/reinitialize Matter.js canvas/world/engine/instance

How to completely stop/reset/reinitialize Matter.js canvas/world/engine/instance

I have an instance of Matterjs on the screen such as a game, and want to completely start over from scratch when the user/player clicks a "new game" button:

525
How does setInterval() run independently of sequential execution?

How does setInterval() run independently of sequential execution?

I'm a beginner in software developmentTo my knowledge, JavaScript runs sequentially from left to right, top to bottom, only skipping lines and returning carriages when functions are called

170