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

6
  • 2
    Does this answer your question? How do I remove a property from a JavaScript object? Commented Oct 26, 2022 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 Commented Oct 26, 2022 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. Commented Oct 26, 2022 at 12:44
  • It might be easier if sponsorship was an array of objects instead. Commented Oct 26, 2022 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 Commented Oct 26, 2022 at 12:47

1 Answer 1

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] }
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

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] } } }});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.