Ich möchte alle Kennwortwerte von einem Objekt in allen Objektebenen aktualisieren:

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.

Gibt es eine API-Methode wie lodash _.set(...)?

2
Hemã Vidal 18 Apr. 2018 im 22:40

4 Antworten

Beste Antwort

Einfache rekursive Lösung, Umgang mit Objekten und Arrays, Mutieren von Eingaben -

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
Ben West 18 Apr. 2018 im 20:07
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);
0
Michio 18 Apr. 2018 im 20:06
 function* deepIterate(obj) {
  yield obj;
  for(const value of Object.values(obj)) 
   if(typeof value === "object")
     yield* deepIterate(value);
 }

Welches kann verwendet werden als:

for(const el of deepIterate(obj))
  if(el.password) el.password = "******";
3
Jonas Wilms 18 Apr. 2018 im 20:01
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

1
Maxwelll 18 Apr. 2018 im 19:57