如何在所有级别的键中更改对象的值?

时间:2018-04-18 19:40:06

标签: javascript node.js object

我想更新所有对象级别中对象的所有密码值:

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.

是否有像lodash _.set(...)这样的API方法?

4 个答案:

答案 0 :(得分:3)

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

可以用作:

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

答案 1 :(得分:2)

简单的递归解决方案,处理对象和数组,改变输入 -

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 :(得分:1)

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

答案 3 :(得分:0)

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