Home > Software design >  How can I merge this object into another one to update in React?
How can I merge this object into another one to update in React?

Time:09-29

let's suppose I have the following object in React:

   {
    name: 'John Max',
    plan: {
        active: true
    }
   }

And then, I have the following object:

{ fields: { "plan.active": false } }

How can I adapt this object in order to replace with the current object?

So in this example, the plan active would become false instead of true, that would be the only change.

CodePudding user response:

You can implement a simple function that traverses the object by passing a path, that you can take from splitting your object key on the dots.

Something like this:

setpath = ([p,...ps], v, o) => ps.length ? setpath(ps, v, o[p]) : o[p] = v


data = { name: "John Max", plan: { active: true } }
input = { fields: { "plan.active": false } }

let [path, val] = Object.entries(input.fields)[0]  // path="plan.active", val=false

setpath(path.split("."), val, data)
console.log(data)  // {name: "John Max", plan: {active: true}}

If you plan to have multiple path-like fields in under fields, and want to update all of them in the object, you can use Array.foreach:

Object.entries(input.fields).forEach(([p,v]) => setpath(p.split("."), v, data))

CodePudding user response:

Note Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

 setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});
  • Related