How to use the cloneDeep function from lodash

Find comprehensive JavaScript lodash.cloneDeep code examples handpicked from public code repositorys.

lodash.cloneDeep is a JavaScript function that creates a deep copy of an object or an array.

2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
* var characters = [
*   { 'name': 'barney', 'age': 36 },
*   { 'name': 'fred',   'age': 40 }
* ];
*
* var deep = _.cloneDeep(characters);
* deep[0] === characters[0];
* // => false
*
* var view = {
fork icon73
star icon711
watch icon29

+ 3 other calls in file

450
451
452
453
454
455
456
457
458
459
  state: this.state || 'standalone',
  capacity: this.capacity || 0,
  lastModified: this.lastModified?.toJSON(),
  lastChecked: this.lastChecked?.toJSON(),
  firstClaim: this.firstClaim?.toJSON(),
  recentTasks: _.cloneDeep(this.recentTasks),
  lastDateActive: this.lastDateActive?.toJSON(),
  quarantineUntil: this.quarantineUntil?.toJSON(),
  quarantineDetails: this.quarantineDetails || [],
};
fork icon238
star icon317
watch icon18

+ 3 other calls in file

How does lodash.cloneDeep work?

lodash.cloneDeep is a function in the Lodash library that creates a deep copy of a given object or array. When lodash.cloneDeep is called with an object or array as its argument, it creates a new object or array with the same properties or elements as the original, but all nested objects or arrays are also copied recursively. This means that the resulting copy is completely independent of the original object or array, with no references or shared memory between the two. lodash.cloneDeep can be used to create a copy of an object or array that you can modify without affecting the original object or array, which can be useful in situations where you need to manipulate data in a controlled and reversible manner. However, it's worth noting that lodash.cloneDeep can be an expensive operation, especially for large or deeply nested objects, so you should use it with care and only when necessary.

118
119
120
121
122
123
124
125
126
127
workerType: workerType,
taskQueueId: this.taskQueueId,
schedulerId: this.schedulerId,
projectId: this.projectId,
taskGroupId: this.taskGroupId,
dependencies: _.cloneDeep(this.dependencies),
requires: this.requires,
routes: _.cloneDeep(this.routes),
priority: this.priority,
retries: this.retries,
fork icon238
star icon317
watch icon18

+ 8 other calls in file

188
189
190
191
192
193
194
195
196
197
  const diff = process.hrtime(startTime);
  v0Time = diff[0] * NS_PER_SEC + diff[1];
  // Comparison is happening in async and after return from here
  // this object is getting modified so comparison was failing to
  // avoid that we are cloning it.
  return _.cloneDeep(v0Result.output);
} catch (error) {
  v0Result.error = {
    message: error.message,
    statusCode: getErrorStatusCode(error),
fork icon77
star icon55
watch icon19

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const _ = require("lodash");

// Define an original object with nested properties
const originalObj = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
  },
};

// Create a deep copy of the original object using lodash.cloneDeep
const newObj = _.cloneDeep(originalObj);

// Modify a nested property of the new object
newObj.address.city = "Newtown";

// Output the original and new objects to the console
console.log(originalObj);
console.log(newObj);

In this example, we start by defining an original object that contains some nested properties. We then create a deep copy of the original object using lodash.cloneDeep. We modify a nested property of the new object by changing the city from 'Anytown' to 'Newtown'. We then output both the original and new objects to the console using console.log. The output of this example will show that the original object remains unchanged, while the new object has been modified: css Copy code

109
110
111
112
113
114
115
116
117
118
119
  return message;
};


const processEvent = (inputEvent) => {
  let message;
  const event = _.cloneDeep(inputEvent);
  const shopifyTopic = getShopifyTopic(event);
  delete event.query_parameters;
  switch (shopifyTopic) {
    case IDENTIFY_TOPICS.CUSTOMERS_CREATE:
fork icon77
star icon54
watch icon20

1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
if (challenge.legacy.selfService) {
  // prettier-ignore
  sendSubmittedEmail = data.status === constants.challengeStatuses.Draft && challenge.status !== constants.challengeStatuses.Draft;

  if (data.metadata && data.metadata.length > 0) {
    let dynamicDescription = _.cloneDeep(data.description || challenge.description);
    for (const entry of data.metadata) {
      const regexp = new RegExp(`{{${entry.name}}}`, "g");
      dynamicDescription = dynamicDescription.replace(regexp, entry.value);
    }
fork icon45
star icon17
watch icon0

110
111
112
113
114
115
116
117
118
119
120
121


  return latestRules;
};


export const updateUserSyncRecords = async (uid, records, appMode) => {
  const latestRules = _.cloneDeep(records);
  // Check if it's team syncing. We might not want to write some props like "isFavourite" to this node. Instead, we can write it to userConfig node
  if (window.currentlyActiveWorkspaceTeamId) {
    const syncRuleStatus = true;
    // localStorage.getItem("syncRuleStatus") === "true" || false;
fork icon34
star icon619
watch icon22

105
106
107
108
109
110
111
112
113
114
115
116


  return localRecords;
};


export const updateUserSyncRecords = async (uid, records, appMode) => {
  const localRecords = _.cloneDeep(records);
  // Check if it's team syncing. We might not want to write some props like "isFavourite" to this node. Instead, we can write it to userConfig node
  if (window.currentlyActiveWorkspaceTeamId) {
    const syncRuleStatus =
      localStorage.getItem("syncRuleStatus") === "true" || false;
fork icon33
star icon614
watch icon22

+ 5 other calls in file

16
17
18
19
20
21
22
23
24
25
26
  return _.unset(object, path);
};


exports.assignWithSet = (object, ...sources) => {
  while (sources.length) {
    const source = _.cloneDeep(sources.shift());
    Object.entries(source).forEach(([key, value]) => {
      if (value === undefined) {
        return unset(object, key);
      }
fork icon59
star icon212
watch icon8

70
71
72
73
74
75
76
77
78

const origGetPuppeteerFn = session.getPuppeteer;
let capsBeforeReset;

origGetPuppeteerFn.callsFake(() => {
    capsBeforeReset = _.cloneDeep(session.capabilities);
});

const browser = mkBrowser_({browserWSEndpoint: 'ws://new.endpoint/devtools'});
fork icon56
star icon556
watch icon11

+ 4 other calls in file

19
20
21
22
23
24
25
26
27
28
CIPHER_KEY: process.env.CIPHER_KEY,
CIPHER_IV_KEY: process.env.CIPHER_IV_KEY,

log: function log() {
  const { log, ...config } = this;
  const escapedConfig = _.cloneDeep(config);
  escapedConfig.REDIS_PASSWORD = '****';
  escapedConfig.ACCESS_TOKEN_SECRET = '****';
  escapedConfig.REFRESH_TOKEN_SECRET = '****';
  escapedConfig.RESET_TOKEN_SECRET = '****';
fork icon105
star icon261
watch icon16

+ 3 other calls in file

3
4
5
6
7
8
9
10
11
12
13
14
const logger = require('../logger')
const _ = require('lodash')
const createCheckName = require('./lib/createCheckName')


const createChecks = async (context, payload, actionObj) => {
  const params = _.cloneDeep(payload)
  params.name = createCheckName(params.name)


  // Note: octokit (wrapped by probot) requires head_branch.
  // Contradicting API docs that only requires head_sha
fork icon104
star icon596
watch icon12

+ 11 other calls in file

52
53
54
55
56
57
58
59
60
61
module.exports.chunk               = _.chunk;
module.exports.chunkAll            = _.chunkAll;
module.exports.chunkContrib        = _.chunkContrib;
module.exports.clamp               = _.clamp;
module.exports.clone               = _.clone;
module.exports.cloneDeep           = _.cloneDeep;
module.exports.cloneDeepWith       = _.cloneDeepWith;
module.exports.cloneWith           = _.cloneWith;
module.exports.collate             = _.collate;
module.exports.compact             = _.compact;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

374
375
376
377
378
379
380
381
382
383
if (mixinOptions.resolvers) {
	resolvers = _.cloneDeep(mixinOptions.resolvers);
}

if (mixinOptions.schemaDirectives) {
	schemaDirectives = _.cloneDeep(mixinOptions.schemaDirectives);
}

let queries = [];
let mutations = [];
fork icon54
star icon96
watch icon8

+ 7 other calls in file

418
419
420
421
422
423
424
425
426
427
        return cloneDeep(cachedItem.response)
    }
}

response = await f.apply(listAdapter, args)
const copiedResponse = cloneDeep(response)

// Note: This solution does not cache complex requests.
//       Request is considered complex if it has relations in its where query/condition.
//       Check queryIsComplex docstring for details
fork icon12
star icon32
watch icon10

219
220
221
222
223
224
225
226
227
228
	(t) => t.schoolId === res.locals.currentSchool,
);
const studentsOfCurrentSchool = students.filter(
	(s) => s.schoolId === res.locals.currentSchool,
);
const substitutions = _.cloneDeep(teachersOfCurrentSchool);

// map course times to fit into UI
(course.times || []).forEach((time, count) => {
	time.duration = time.duration / 1000 / 60;
fork icon11
star icon31
watch icon16

+ 4 other calls in file

218
219
220
221
222
223
224
225
226
227
228
function testPassed(failed, passed) {
  return failed <= 0 && passed >= 1;
}


function setOptions(reportName, reportPath = 'features/') {
  const myOptions = lodash.cloneDeep(options);
  myOptions.metadata.Platform = process.platform;
  myOptions.name = `Seed-Test Report: ${reportName}`;
	if (reportPath !== 'features/') {
    myOptions.jsonDir = `${reportPath}`;
fork icon8
star icon18
watch icon2

242
243
244
245
246
247
248
249
250
251
252
253
}


async function addAnnotatorFromSlack(pro, slackUser) {
    console.log(`[ PROJECT ] Service addAnnotatorFromSlack`);
    let annotators = [], completeCase = [], assigneeList = [];
    annotators = _.cloneDeep(pro.annotator);
    annotators.push(slackUser)


    //to new the assigned case according to the new annotators list
    assigneeList = await evenlyDistributeTicket(annotators, pro.totalCase, pro.maxAnnotation);
fork icon15
star icon37
watch icon8

+ 7 other calls in file

336
337
338
339
340
341
342
343
344
345
        type: "Endpoint"
    }
];

let qidoLevelKeys = Object.keys(qidoRetAtt);
let qidoAtt = _.cloneDeep(qidoRetAtt);
for (let i = 0; i < qidoLevelKeys.length; i++) {
    let levelTags = Object.keys(qidoRetAtt[qidoLevelKeys[i]]);
    for (let x = 0; x < levelTags.length; x++) {
        let nowLevelKeyItem = qidoAtt[qidoLevelKeys[i]];
fork icon8
star icon35
watch icon5

+ 5 other calls in file

878
879
880
881
882
883
884
885
886
887
        }
      ]
    }
  }
];
const rawStandardAndQuery = _.cloneDeep(raw);
rawStandardAndQuery.expTreeInclude.childInstances[0].modifiers = [
  {
    id: 'ActiveOrConfirmedAllergyIntolerance',
    name: 'Active Or Confirmed',
fork icon14
star icon34
watch icon9

+ 53 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)