Performing a deep copy of a JavaScript object using Lodash in JavaScript

The process involves obtaining the value of a certain property, and then adding the final part of the path as a property to the outcome object. Two solutions can be implemented for this task. One solution involves using the omit method described in the following link: https://lodash.com/docs/4.17.4#omit. The other method involves utilizing the ES object rest/spread proposal. If the goal is to select certain properties from a complex object based on a specified path, then both of these solutions can be used.


Solution 1:

It’s possible to perform deep destructuring without the need for lodash.

var object = {
  a: 'a',
  b: 'b',
  c: {
      d: 'd'
  }
}

const { a, b, c :{ d }} = object;

console.log(a,b,d);

const obj = {a, b, d};

console.log(obj);


Solution 2:


If you are determined to utilize Lodash, then you may want to contemplate making use of the _.get() method.

_.get(object, 'c.d');

Therefore, to obtain the desired characteristics, you should consider the following.

const selectedProps = {
  ..._.pick(object, ['a', 'b']),
  _.get(object, 'c.d')
}


Solution 3:


A new function can be formed, identified as

flatPick()

. This function can traverse through the array of paths. By using

_.get()

, the corresponding value of

path

can be obtained. Additionally,

_.set()

can be utilized to append the final component of the path as a property on the resultant object.

function flatPick(object, paths) {
  const o = {};

  paths.forEach(path => _.set(
    o,
    _.last(path.split('.')),
    _.get(object, path)
  ));

  return o;
}

var object = {
  a: 'a',
  b: 'b',
  c: {
    d: 'd',
    e: {
      f: 'f'
    }
  }
};

var result = flatPick(object, ['a', 'b', 'c.d', 'c.e.f']);

console.log(result);

Frequently Asked Questions