Search code examples
javascriptlodash

Using lodash, how do I set multiple properties on an object?


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',
}

Solution

  • 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 ;)