如何遍历可能更改obj(因此需要更改的变量)的Object.Keys(obj)?
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>
我相信重要的部分在于
${Object.keys(selectedDevice + 'SKUs').map(key => (
当selectedDevice更改时,我是否需要另一个模板文字来指向其他对象?我猜想[selectedDevice +'SKUs]表达式返回一个字符串,因此Object.keys无法从字符串中检测到对象?
如果可以将对象包装在另一个对象中,则可以从容器对象中以字符串键的形式访问这些对象。例如,如果将modelBasicSKUs
设置为全局对象,则可以使用window['modelBasicSKUs']
或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]));