2

I want to update object key name on setState. I have this object:

let obj = {
      sponsorship: {
        a: {
          task: "x",
          todo: "y"
        },
        b: {
          task: "x1",
          todo: "y2"
        }
      }
    };
    setForm(obj);

Now want to rename one of object key name:

setForm({
      ...form,
      sponsorship: {
        ...form.sponsorship,
        [newName]: { ...form.sponsorship[oldName] }
      }
    });

I tried this but it will add new object not replace. also tried this:

setForm({
      ...form,
      sponsorship: {
        [newName]: { ...form.sponsorship[oldName] }
      }
    });

But this will remove all prev object. but I need to for example rename a key to c

Demo

Apostolos
  • 10,033
  • 5
  • 24
  • 39
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51
  • 2
    Does this answer your question? [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – jonrsharpe Oct 26 '22 at 12:43
  • You need to manipulate the object just like you would do with any other JS object. Also it's preferable to use a callback when using the current state value to calculate the next one – GalAbra Oct 26 '22 at 12:43
  • 1
    Sometimes you can use `const { dontCare, ...doCare } = obj`, but not when the property name is dynamic. Create the new sponsorships argument, then delete the old name. – jonrsharpe Oct 26 '22 at 12:44
  • It might be easier if `sponsorship` was an array of objects instead. – Andy Oct 26 '22 at 12:46
  • @jonrsharpe I don't want to remove actually.. I know it's a way, but is there any way to rename? I want to do this in setState – Jack The Baker Oct 26 '22 at 12:47
  • That _is_ how you rename - add as new name, remove as old name. – jonrsharpe Oct 26 '22 at 12:56

1 Answers1

3

If you don't want to delete a property and you are searching for an alternative way to do it, you can filter the sponsorship properties and return a new object without the oldValue

setForm({
  ...form,
  sponsorship: {
    ...Object.fromEntries(
      Object.entries(form.sponsorship)
      .filter(([key]) => oldName !== key)
    ),
    [newName]: { ...form.sponsorship[oldName] }
  }
});
Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • Ideally when new value depends on the previous one you should pass a callback function which gets current state value as the first argument. `setForm(state => { const {[oldName]: _oldKey, ...restSponsorship} = state.sponsorship; return { ...state, sponsorship: { ...restSponsorship, [newName]: { ...state.sponsorship[oldName] } } }});` – P. Zietal Oct 26 '22 at 13:02