如何根据txtukuran和txtwarna输入值匹配对应JS对象变量名?
根据尺寸和颜色匹配对应变量名的解决方案
一、规整对象存储(推荐方案)
零散定义的m25kuning、m25putih这类变量直接查找效率低,先把它们统一存入集合,方便后续检索:
// 将所有产品对象存入数组 const productList = [ m25kuning, m25putih, // 其他同类对象依次添加 ]; // 创建对象映射,键为原变量名,值为对应对象 const productMap = { m25kuning, m25putih, // 对应添加其他对象 };
二、获取隐藏输入框的值
从txtukuran和txtwarna中提取目标尺寸与颜色:
const targetSize = document.getElementById('txtukuran').value; const targetColor = document.getElementById('txtwarna').value;
三、匹配对象并获取变量名
先找到符合条件的对象,再从映射中取出对应的变量名:
// 筛选匹配的产品对象 const matchedItem = productList.find(item => item.ukuran === targetSize && item.warna === targetColor ); if (matchedItem) { // 从映射中提取对应的变量名 const [variableName] = Object.entries(productMap).find(([key, val]) => val === matchedItem); console.log('匹配到的变量名:', variableName); // 同步更新页面展示元素 document.getElementById('ukVal').textContent = matchedItem.ukuran; document.getElementById('hrgVal').textContent = matchedItem.harga; document.getElementById('wrVal').textContent = matchedItem.warna; } else { console.log('没有找到匹配的产品'); }
备选方案:直接遍历全局对象(不推荐)
如果不想额外维护集合,可直接遍历全局对象查找,但容易误匹配无关变量:
const targetSize = document.getElementById('txtukuran').value; const targetColor = document.getElementById('txtwarna').value; let matchedVarName = null; // 遍历全局对象属性,筛选符合条件的对象 for (const key in window) { const currentObj = window[key]; if (typeof currentObj === 'object' && currentObj.ukuran === targetSize && currentObj.warna === targetColor) { matchedVarName = key; break; } } if (matchedVarName) { console.log('匹配到的变量名:', matchedVarName); const matchedProduct = window[matchedVarName]; // 更新展示元素 document.getElementById('ukVal').textContent = matchedProduct.ukuran; document.getElementById('hrgVal').textContent = matchedProduct.harga; document.getElementById('wrVal').textContent = matchedProduct.warna; } else { console.log('无匹配产品'); }
关键提示
- 优先使用集合存储的方式,安全性和可维护性更高。
- 确保输入框的值与对象属性值类型一致(比如均为字符串),避免匹配失败。
内容的提问来源于stack exchange,提问作者Andrea Saturnus
相关产品推荐
相关产品推荐

