问题
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