Search code examples
javascriptobjectreact-hookspropertiespropertypath

How to access and edit an object value by iterating on a path?


Having this following data structure :

const foo = [
    {
        a: 'xxx',
        b: 'xxx',
        c: {
            e: 'xxx',
            ...
        }
    }
    ...
]

Is it possible to access the value of e with this path object

const path = [0, 'c', 'e']

and edit it ?

I tried by doing

setResponseState(prevState => {
    let data = prevState.responseData
    path.forEach(id => data = data[id])

    data = {}
    return prevState
})

path being a context value but I found out data was a copy and therefore wasn't saved in the react state

Thank you


Solution

  • If you modify updating the last value in forEach as below should work for editing the object. Basically this avoid overriding the object reference and only update the value.

    const foo = [
      {
        a: "xxx",
        b: "xxx",
        c: {
          e: "xxx",
        },
      },
    ];
    
    
    const path = [0, "c", "e"];
    
    setResponseState((prevState) => {
      let data = prevState.responseData;
      path.forEach((id, i) =>
        i === path.length - 1 ? (data[id] = {}) : (data = data[id])
      );
      return prevState;
    });
    

    Check this sample mutating the object

    const foo = [
      {
        a: "xxx",
        b: "xxx",
        c: {
          e: "xxx",
        },
      },
    ];
    
    const path = [0, "c", "e"];
    
    
      let data = foo;
      path.forEach((id, i) =>
        i === path.length - 1 ? (data[id] = {}) : (data = data[id])
      );
    
    console.log(foo)