如何修改对象所有层级的password值?是否有类似lodash _.set的API?
Nice question! Lodash doesn't have an out-of-the-box API that exactly matches your proposed updateDeeply function (unlike _.set, which targets a specific nested path rather than all occurrences of a key). But you can easily build this functionality using either Lodash utilities or vanilla JavaScript, and both approaches will modify the original object as you requested.
Solution 1: Using Lodash
Lodash's _.forEach makes it simple to traverse both objects and arrays. Combine it with recursion to dive into nested structures and replace every instance of your target key:
const updateDeeply = (obj, targetKey, newValue) => { _.forEach(obj, (value, key) => { // Replace the value if we've found the target key if (key === targetKey) { obj[key] = newValue; } // Recurse into nested objects/arrays (skip functions) else if (_.isObject(value) && !_.isFunction(value)) { updateDeeply(value, targetKey, newValue); } }); return obj; }; // Example usage 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', '********'); console.log(obj); // Result: // { // user: { name: 'u1', password: '********' }, // subUsers: [ { name: 'u2', password: '********' } ], // whereverLevel: { password: '********' } // }
Solution 2: Vanilla JavaScript (No Lodash)
If you'd rather avoid external libraries, a recursive vanilla JS function works just as effectively. This also modifies the original object:
const updateDeeply = (obj, targetKey, newValue) => { // Skip non-objects, null values, and functions if (typeof obj !== 'object' || obj === null || typeof obj === 'function') { return obj; } // Handle arrays by iterating over each element if (Array.isArray(obj)) { obj.forEach(item => updateDeeply(item, targetKey, newValue)); } // Handle objects by looping through each key else { Object.keys(obj).forEach(key => { if (key === targetKey) { obj[key] = newValue; } else { updateDeeply(obj[key], targetKey, newValue); } }); } return obj; }; // Same usage as above updateDeeply(obj, 'password', '********');
Extra Tips
- Immutability: If you don't want to modify the original object, adjust the code to create copies first. For Lodash, use
_.cloneDeep(obj)at the start of the function. For vanilla JS, spread objects/arrays when processing them. - Reusability: Both functions work for any target key, not just
password—feel free to reuse them for other fields you need to update across all nested levels.
内容的提问来源于stack exchange,提问作者Hemã Vidal

