简体   繁体   中英

Change nested property of an Object in Javascript

Having an object of this form:

const myObj = {
    'firstA': {
       'secondC': [1,2,3],
       'secondD': [4,5,6],
    },
    'firstB':{
       'secondE': [0,0,0],
       'secondF': [1,1,1],
  },
}

I'm accessing one of its children's array, for example secondC .

In this case, the application uses appValue = myObj.firstA.secondC .

The values secondC , secondD , secondE and secondF are on a dropdown so the user can click on one of them and the application must reload with the new data.

Is there a way to get that value if it is not specified the "middle" node? (on dropdown there is no firstA or firstB )

You'll have to keep a track of the middle key also like

{
  "secondC":"fristA",
  "secondD":"fristA",
}

Then when the user selects from the dropdown you can lookup in the mapping and know the middle key. You can create this mapping once and use it as a cache instead if searching through everytime.

Here is the code to generate the mapping between subkeys and middle keys:

 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)

Hope this helps !

You can use a function like Object.entries to iterate your object and find the key you are looking for:

 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]);

You can transform your object into a flat one, and use it instead:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM