使用lodash或原生JS批量设置对象指定路径属性为指定值的方法
方法1:使用Lodash实现
Lodash已经封装了深拷贝和路径设值的工具方法,代码非常简洁:
const _ = require('lodash') const list = [ 'creditCardNumber', 'orderDetails.amount', 'customerInformation.details.email', ] const someObj = { creditCardNumber: '000 0000 0000 0000', orderNumber: '1234', orderDetails: { amount: 20, date: 'some date' }, customerInformation: { details: { email: 'some@email.com', joinedOn: 'someDate' } }, someOtherProp: 'some value', } // 先深拷贝避免修改原对象,再遍历路径统一设值 const hiddenObj = _.cloneDeep(someObj) list.forEach(path => _.set(hiddenObj, path, '[HIDDEN]'))
方法2:原生JS实现
自己实现深拷贝和路径设值的工具函数即可,不需要引入第三方依赖:
const list = [ 'creditCardNumber', 'orderDetails.amount', 'customerInformation.details.email', ] const someObj = { creditCardNumber: '000 0000 0000 0000', orderNumber: '1234', orderDetails: { amount: 20, date: 'some date' }, customerInformation: { details: { email: 'some@email.com', joinedOn: 'someDate' } }, someOtherProp: 'some value', } // 深拷贝工具 function deepClone(obj) { if (obj === null || typeof obj !== 'object') return obj if (obj instanceof Date) return new Date(obj) if (Array.isArray(obj)) return obj.map(item => deepClone(item)) const clone = {} for (const key in obj) { if (obj.hasOwnProperty(key)) clone[key] = deepClone(obj[key]) } return clone } // 按路径设值工具 function setPathValue(obj, path, value) { const keys = path.split('.') let current = obj for (let i = 0; i < keys.length - 1; i++) { const key = keys[i] if (!current[key] || typeof current[key] !== 'object') current[key] = {} current = current[key] } current[keys.at(-1)] = value } // 生成处理后的对象 const hiddenObj = deepClone(someObj) list.forEach(path => setPathValue(hiddenObj, path, '[HIDDEN]'))
两种实现都不会修改原对象,输出结果完全符合要求。
内容的提问来源于stack exchange,提问作者nkhil
相关产品推荐
相关产品推荐

