0

I need to add an id number to the nested array in data called action. The code I'm using is:

const { data } = this.state
        const newData = Object.assign([...data.action], Object.assign([...data.action],{0:'id' }))

but this code is not working. The result I am looking for is: {id:1 action: "user...}

enter image description here

1 Answer 1

2

You can just use the spread operator.

const newData = {
  ...data,
  action: {
    ...data.action,
    id: 1
  }
};

If action is an array, you can try something like this:

const newAction = data.action.map((actionItem, index) => ({
  ...actionItem,
  id: index + 1
}));
const newData = {
  ...data,
  action: newAction
};
Sign up to request clarification or add additional context in comments.

10 Comments

How do I make id add +1 for each item in the array?
This was helpful but I need id inside the array objects that inside action.
Now it says id: NaN
Maybe, it is undefined. Try id: typeof actionItem.id === 'undefined' ? 1 : actionItem.id + 1
And I need it to be the first property in the array.
|

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.