array.ts 955 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import { toPath } from 'lodash'
  2. function getValue<ValueObject>(container: ValueObject, path: string) {
  3. const elements = toPath(path)
  4. let obj: any = container
  5. for (let element of elements) {
  6. obj = obj[element as keyof object]
  7. }
  8. return obj
  9. }
  10. function recursiveSet<ValueObject>(object: ValueObject, path: string[], value: any): any {
  11. if (path.length === 0) {
  12. return value
  13. }
  14. if (object instanceof Array) {
  15. const index = parseInt(path[0])
  16. return [
  17. ...object.slice(0, index),
  18. recursiveSet(object[index], path.slice(1), value),
  19. ...object.slice(index + 1)
  20. ]
  21. } else {
  22. const index = path[0]
  23. return {
  24. ...object,
  25. [index]: recursiveSet(object[index as keyof object], path.slice(1), value)
  26. }
  27. }
  28. }
  29. function setValue(container: object | any[], path: string, value: any) {
  30. const elements = toPath(path)
  31. return recursiveSet(container, elements, value)
  32. }
  33. export { getValue, setValue }