object-utils.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. export function deepCopy<T>(obj: T, keys?: string[]): T {
  2. // Handle Object
  3. if (obj instanceof String) {
  4. return (obj + '') as unknown as T;
  5. } else if (obj instanceof Date) {
  6. return new Date(obj.getTime()) as unknown as T;
  7. } else if (obj instanceof Array) {
  8. const copy = Array(obj.length);
  9. for (let i = 0, len = obj.length; i < len; i++) {
  10. copy[i] = deepCopy(obj[i]);
  11. }
  12. return copy as unknown as T;
  13. } else if (obj instanceof Set) {
  14. const copy = new Set();
  15. obj.forEach(value => {
  16. copy.add(deepCopy(value));
  17. });
  18. return copy as unknown as T;
  19. } else if (obj instanceof Map) {
  20. const copy = new Map();
  21. obj.forEach((value, key) => {
  22. copy.set(key, deepCopy(value));
  23. });
  24. return copy as unknown as T;
  25. } else if (obj instanceof Object) {
  26. const copy: { [key: string]: any } = {};
  27. for (const attr in obj) {
  28. if (typeof keys !== 'undefined' && !keys.includes(attr)) {
  29. continue;
  30. }
  31. if (Object.getOwnPropertyNames(obj).includes(attr)) copy[attr] = deepCopy((obj as { [key: string]: any })[attr]);
  32. }
  33. return copy as unknown as T;
  34. } else {
  35. return obj;
  36. }
  37. }