DEV Community

Discussion on: Best way to copy an object in JavaScript?

Collapse
 
xenon15 profile image
Ashwani Sindhu

I use this utility function for deep cloning the objects in vanilla JavaScript. It handles string properties, symbol properties and circular references in the input object.

function cloneDeep(data, map = new Map()) {
  if (data === undefined || data === null || typeof data !== 'object') {
    return data;
  }
  if (map.has(data)) {
    return map.get(data);
  }
  const result = Array.isArray(data) ? [] : {};
  map.set(data, result);
  const allKeys = [...Object.keys(data), ...Object.getOwnPropertySymbols(data)]
  for (const key of allKeys) {
      result[key] = cloneDeep(data[key], map);
  }

  return result;
}

Enter fullscreen mode Exit fullscreen mode