How to change the value of an object in all levels of keys?

别来无恙 提交于 2021-02-19 05:56:05

问题


I want to update all password values from an object in all object levels:

let obj = {
  user: {
    name: 'u1', 
    password: 'do not show me'
  },
  subUsers: [
    {
      name: 'u2', 
      password: 'do not show me as well'
    }
  ],
  whereverLevel : {
    password: 'please, hide me too'
  }
}

updateDeeply(obj, 'password', '********') //mutates obj and changes all password values in all object levels.

Is there an API method like lodash _.set(...)?


回答1:


Simple recursive solution, handling objects and arrays, mutating input –

function deepReplace ( x, targetKey, replaceWith ) {
    if ( Array.isArray( x ) ) {
        x.forEach( x => deepReplace( x, targetKey, replaceWith ) );
    } else if ( typeof x === 'object' ) {
        for ( var key in x ) {
            if ( key === targetKey ) x[ key ] = replaceWith;
            if ( typeof x[ key ] === 'object' ) {
                 deepReplace( x[ key ], targetKey, replaceWith );
            }
        }
    }
}



回答2:


 function* deepIterate(obj) {
  yield obj;
  for(const value of Object.values(obj)) 
   if(typeof value === "object")
     yield* deepIterate(value);
 }

Which can be used as:

for(const el of deepIterate(obj))
  if(el.password) el.password = "******";



回答3:


function updateKeys(keyName, value, input) {
  Object.keys(input).map(key => {
    if (key === keyName) {
      input[key] = value;
    } else if (Array.isArray(input[key])) {
      input[key].map(e => updateKeys(keyName, value, e));
    } else if (input[key] && input[key][keyName]) {
      input[key][keyName] = value;
    }
  });
}

https://repl.it/repls/AveragePalegreenFrontend




回答4:


let obj = {
    user: {
        name: 'u1',
        password: 'do not show me'
    },
    subUsers: [
        {
            name: 'u2',
            password: 'do not show me as well'
        }
    ],
    whereverLevel: {
        password: 'please, hide me too'
    }
};

// Use recursion.
function updateDeeply(obj, key, value) {
    Object.keys(obj).forEach(function (_key) {
        // Note that Object.keys() works on arrays as well.
        if (_key === key) {
            obj[_key] = value;
        } else if (typeof obj[_key] === 'object' || Array.isArray(obj[_key])) {
            // Make recursive call.
            updateDeeply(obj[_key], key, value);
        }
    });
}

updateDeeply(obj, 'password', 'replace');

console.log(obj);


来源:https://stackoverflow.com/questions/49907772/how-to-change-the-value-of-an-object-in-all-levels-of-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!