index.mjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. function get(obj, path) {
  2. if (obj == null)
  3. return void 0;
  4. let value = obj;
  5. for (let i = 0; i < path.length; i++) {
  6. if (value == null || value[path[i]] == null)
  7. return void 0;
  8. value = value[path[i]];
  9. }
  10. return value;
  11. }
  12. function set(obj, value, path) {
  13. if (path.length === 0)
  14. return value;
  15. const idx = path[0];
  16. if (path.length > 1) {
  17. value = set(
  18. typeof obj !== "object" || obj === null || !Object.prototype.hasOwnProperty.call(obj, idx) ? Number.isInteger(Number(path[1])) ? [] : {} : obj[idx],
  19. value,
  20. Array.prototype.slice.call(path, 1)
  21. );
  22. }
  23. if (Number.isInteger(Number(idx)) && Array.isArray(obj))
  24. return obj.slice()[idx];
  25. return Object.assign({}, obj, { [idx]: value });
  26. }
  27. function unset(obj, path) {
  28. if (obj == null || path.length === 0)
  29. return obj;
  30. if (path.length === 1) {
  31. if (obj == null)
  32. return obj;
  33. if (Number.isInteger(path[0]) && Array.isArray(obj))
  34. return Array.prototype.slice.call(obj, 0).splice(path[0], 1);
  35. const result = {};
  36. for (const p in obj)
  37. result[p] = obj[p];
  38. delete result[path[0]];
  39. return result;
  40. }
  41. if (obj[path[0]] == null) {
  42. if (Number.isInteger(path[0]) && Array.isArray(obj))
  43. return Array.prototype.concat.call([], obj);
  44. const result = {};
  45. for (const p in obj)
  46. result[p] = obj[p];
  47. return result;
  48. }
  49. return set(
  50. obj,
  51. unset(
  52. obj[path[0]],
  53. Array.prototype.slice.call(path, 1)
  54. ),
  55. [path[0]]
  56. );
  57. }
  58. function deepPickUnsafe(obj, paths) {
  59. return paths.map((p) => p.split(".")).map((p) => [p, get(obj, p)]).filter((t) => t[1] !== void 0).reduce((acc, cur) => set(acc, cur[1], cur[0]), {});
  60. }
  61. function deepPick(obj, paths) {
  62. return deepPickUnsafe(obj, paths);
  63. }
  64. function deepOmitUnsafe(obj, paths) {
  65. return paths.map((p) => p.split(".")).reduce((acc, cur) => unset(acc, cur), obj);
  66. }
  67. function deepOmit(obj, paths) {
  68. return deepOmitUnsafe(obj, paths);
  69. }
  70. export { deepOmit, deepOmitUnsafe, deepPick, deepPickUnsafe };