dot-path-value icon indicating copy to clipboard operation
dot-path-value copied to clipboard

Added relative path get and set

Open ruisilva450 opened this issue 2 years ago • 0 comments

I'm coming from a specific use case on my side where I have an initial path and want to manipulate the object with a relative path from the initial. After getting it working I thought it could be useful to include it on your package.

Explanation

We are going to start with this object:

const obj = {
  a: {
    b: 'hello',
    d: [
      {
        e: 'world',
      },
    ],
  },
};

This PR is composed into two parts:

getByRelativePath(obj, path, relativePath)

  1. I know the initial path 'a.d.0'
  2. I want to get the value that's relative to the initial path ../../b
  3. I call getByRelativePath(obj, 'a.d.0', '../../b')
  4. It should be able to step back twice ('../../' takes the context to a) and step forward once ('b' takes the context to a.b)
  5. I'm expected to get 'hello'

setByRelativePath(obj, path, relativePath, value)

  1. I know the initial path 'a.d.0'
  2. I want to set the value that's relative to the initial path ../../b
  3. I call setByRelativePath(obj, 'a.d.0', '../../b', 'good morning')
  4. It should be able to step back twice ('../../' takes the context to a) and step forward once ('b' takes the context to a.b)
  5. I'm expected obj.a.b === 'good morning'

Note: Take into account that I'm not well knowledgeable in typescript and learned a good deal with your code. Still I know there is some work to be done on this PR related with that.

Can I get some help on that maybe? :)

ruisilva450 avatar Jun 26 '23 02:06 ruisilva450