如何在所有级别的键中更改对象的值? [英] How to change the value of an object in all levels of keys?

查看:48
本文介绍了如何在所有级别的键中更改对象的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在所有对象级别更新一个对象的所有密码值:

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.

有没有类似 lodash _.set(...) 的 API 方法?

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

推荐答案

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

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

这篇关于如何在所有级别的键中更改对象的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆