1

I have an array with objects that also contain array. How can I push element to that array inside object using useState?

const [list, updateList] = useState([defaultList]);

const defaultList = [
  {
    "name":"Element 1",
    "subList": [{"name": "Element 1"}]
  }
]

How can I update subList in that case?

2 Answers 2

1

If you have one item in your array, you must recreate your array with new/modified data in it.

updateList(state => {
  const stateCopy = [...state]

  stateCopy[index] = {
    ...stateCopy[index],
    subList: [...state[index].subList, newItem]
  }

  return stateCopy
})

Update:

If you want to update based on the item name.

updateList(state => {
  const stateCopy = [...state]
  const indexOfName = stateCopy.findxIndex(item => item.name === name)

  stateCopy[indexOfName] = {
    ...stateCopy[indexOfName],
    subList: [...state[indexOfName].subList, newItem]
  }

  return stateCopy
})
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but what if I have array of objects like this: ` const defaultList = [ { "name":"Element 1", "subList": [{"name": "Element 1"}] }, { "name":"Element 2", "subList": [{"name": "Element 1"}] }, { "name":"Element 3", "subList": [{"name": "Element 1"}] } ] ` How can I target an object by its name?
You'll need to find the index of the item with the name you're looking for. Check the updated answer.
1

Assuming you want to append an item to the sublist of a specific list item, based on index:

function appendSublistItemForItemAtIndex(newItem, index) {
  updateList([
    ...list,
    [index]: {
      ...list[index],
      subList: [
        ...list[index].subList,
        newItem
      ]
    }
  ])
}

Then call this function wherever needed for your component (some callback, in a useEffect hook, etc.)

Comments

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.