0

I have a object named json


let json ={
    c: {
        a1:1,
        b1:{
            a2:6
        }
    }
}

there is a key name b1 whose value is an Object. In that object I want to add a new key value pair b2 : 100.

so the newObj that I want to add


let newObj={
    c: {
        b1:{
            b2:100 // new key-value entry
        }
    }
}

SO that after using spread operator I can modify the json as follows


json ={
    c: {
        a1:1,
        b1:{
            a2:6,
            b2:100
        }
    }
}

The code that I used is as follows:


var json = {...json, ...newObj}

I know this is completely wrong as this gave an undesirable output which is as follows


json={
    c: {
        b1:{
            b2:100
        }
    }
}

I am actually doing a React state update with useState hook where json is a state and setJson will set the json's new state I did it like:


setJson(current => ({
  form : {
    ...current.form,
    ...newObj },
  },
}));

where newObj is an object
newObj = {
  form:{
    a:1,
    b:{
      b1:{
        b2:100, //new key-value pair to be added in b1
      }
    }
  }
}


Please suggest an easy way to update the json state that can be used in that useState hook

What I want I want to merge arbitrary objects to json(merge arbitrary objects (having arbitrary nesting). The nesting could be very deep

singing sun
  • 43
  • 1
  • 8

0 Answers0