在 Javascript 中更改对象的嵌套属性

具有这种形式的对象:


const myObj = {

    'firstA': {

       'secondC': [1,2,3],

       'secondD': [4,5,6],

    },

    'firstB':{

       'secondE': [0,0,0],

       'secondF': [1,1,1],

  },

}

我正在访问其子数组之一,例如secondC.


在这种情况下,应用程序使用appValue = myObj.firstA.secondC.


值secondC、和位于下拉列表中secondD,因此用户可以单击其中一个,应用程序必须重新加载新数据。secondEsecondF


如果未指定“中间”节点,有没有办法获得该值?(在下拉列表中没有firstAor firstB)


SMILET
浏览 205回答 3
3回答

慕勒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 = {&nbsp; 'firstA': {&nbsp; &nbsp; 'secondC': [1, 2, 3],&nbsp; &nbsp; 'secondD': [4, 5, 6],&nbsp; },&nbsp; 'firstB': {&nbsp; &nbsp; 'secondE': [0, 0, 0],&nbsp; &nbsp; 'secondF': [1, 1, 1],&nbsp; },};const $select = document.querySelector('select');const $pre = document.querySelector('pre');const options = Object.entries(myObj)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .reduce((res, [key, obj]) => ({...res, ...obj}), {});&nbsp;&nbsp;Object.keys(options).forEach(key => {&nbsp; const $option = document.createElement('option');&nbsp; $option.value = key;&nbsp; $option.innerText = key;&nbsp; $select.appendChild($option);});$select.addEventListener('change', e => {&nbsp; const key = e.target.value;&nbsp; const value = key ? JSON.stringify(options[key]) : '';&nbsp; $pre.innerHTML = value;});<select>&nbsp; <option>-- Select a property --</option></select><pre></pre>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript