Reputation: 1620
I have a list of properties, like so:
const list = [
'creditCardNumber',
'orderDetails.amount',
'customerInformation.details.email',
]
Given an object like this:
const someObj = {
creditCardNumber: '000 0000 0000 0000',
orderNumber: '1234',
orderDetails: { amount: 20, date: 'some date' },
customerInformation: { details: { email: '[email protected]', joinedOn: 'someDate' } },
someOtherProp: 'some value',
}
Using lodash
, or vanilla JS, is there an easy way to make a copy of the obj, while re-writing the values of locations on the list
array (to the same value for eg: [HIDDEN]
) so we get something like this?
{
const someObj = {
creditCardNumber: '[HIDDEN]',
orderNumber: '1234',
orderDetails: { amount:'[HIDDEN]', date: 'some date' },
customerInformation: { details: { email: '[HIDDEN]', joinedOn: 'someDate' } },
someOtherProp: 'some value',
}
Upvotes: 0
Views: 2650
Reputation: 25401
USING VANILLA JS
Clone object using Object Destructuring and then using forEach add the [HIDDEN]
value
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: "[email protected]",
joinedOn: "someDate"
},
},
someOtherProp: "some value",
};
let clone = { ...someObj };
list.forEach((prop) => {
const splitProp = prop.split(".");
let obj = clone;
splitProp.forEach((p, i, arr) => {
if (i === arr.length - 1) {
obj[p] = `[HIDDEN]`;
} else {
obj = obj[p];
}
});
});
console.log(clone);
Upvotes: 0
Reputation: 44264
Lodash _.set()
accepts dot seperated object paths, so
_.set(obj, 'orderDetails.amount', 'TEST');
Will resolve to:
obj.orderDetails.amount = 'TEST'
Combine that with a loop for each list
item to get the desired result:
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: '[email protected]', joinedOn: 'someDate' } }, someOtherProp: 'some value', }
const newObj = _.clone(someObj);
list.forEach(key => _.set(newObj, key, '[HIDDEN]'));
console.log(newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
{
"creditCardNumber": "[HIDDEN]",
"orderNumber": "1234",
"orderDetails":
{
"amount": "[HIDDEN]",
"date": "some date"
},
"customerInformation":
{
"details":
{
"email": "[HIDDEN]",
"joinedOn": "someDate"
}
},
"someOtherProp": "some value"
}
Note: Using _.clone()
to 'clone' the object ;)
Upvotes: 1