-
慕勒3428872
您还必须跟踪中间键,例如{ "secondC":"fristA", "secondD":"fristA",}然后,当用户从下拉列表中选择时,您可以在映射中查找并知道中间键。如果每次都搜索,您可以创建一次此映射并将其用作缓存。这是生成子键和中间键之间映射的代码:const myObj = { 'firstA': { 'secondC': [1,2,3], 'secondD': [4,5,6], }, 'firstB':{ 'secondE': [0,0,0], 'secondF': [1,1,1], },}const mapping = Object.keys(myObj).reduce((acc,key)=>{ const subKeys = Object.keys(myObj[key]); for(const subkey of subKeys){ acc[subkey] = key } return acc},{})console.log(mapping)
-
噜噜哒
你可以使用一个函数Object.entries来迭代你的对象并找到你正在寻找的键:const myObj = { 'firstA': { 'secondC': [1,2,3], 'secondD': [4,5,6], }, 'firstB':{ 'secondE': [0,0,0], 'secondF': [1,1,1], },}// Let's say the user selected "secondE"let key = "secondE";// Now find it:let [mid, midValue] = Object.entries(myObj).find(([mid, midValue]) => key in midValue);console.log(mid, key, midValue[key]);
-
天涯尽头无女友
您可以将对象转换为平面对象,然后改用它:const myObj = { 'firstA': { 'secondC': [1, 2, 3], 'secondD': [4, 5, 6], }, 'firstB': { 'secondE': [0, 0, 0], 'secondF': [1, 1, 1], },};const $select = document.querySelector('select');const $pre = document.querySelector('pre');const options = Object.entries(myObj) .reduce((res, [key, obj]) => ({...res, ...obj}), {}); Object.keys(options).forEach(key => { const $option = document.createElement('option'); $option.value = key; $option.innerText = key; $select.appendChild($option);});$select.addEventListener('change', e => { const key = e.target.value; const value = key ? JSON.stringify(options[key]) : ''; $pre.innerHTML = value;});<select> <option>-- Select a property --</option></select><pre></pre>