0

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?

CoJanks
  • 109
  • 1
  • 1
  • 9
  • 3
    Has little to do with the Objects. More like how can I access a variable via a string. Be better to have an object and reference it via the object. Otherwise has to be a global variable. – epascarello Feb 12 '20 at 19:52
  • 3
    Don't have variables named `nnnnnnSKUs`; have a master object with keys named `nnnnnnSKUs` and do `masterObjWithSKUKeys[selectedDevice + 'SKUs']` – apsillers Feb 12 '20 at 19:55
  • 1
    https://stackoverflow.com/questions/1920867/get-global-variable-dynamically-by-name-string-in-javascript – epascarello Feb 12 '20 at 20:00

1 Answers1

0

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]));
Addis
  • 2,480
  • 2
  • 13
  • 21