I have booksOwned inside an array of objects, and I want to add another book to "John Doe"'s booksOwned.
const [ownerInfo, setOwnerInfo] = React.useState([
{
owner: "John Doe",
booksOwned: ["To Kill a Mockingbird", "1984"],
},
{
owner: "John Doe Jr",
booksOwned: [
"Harry Potter and the Philosopher's Stone",
"The Lord of the Rings",
],
},
])
This is what I've tried so far, does not seem to work.
let data = ownerInfo
let newBook = "Pride and Prejudice"
//to store currently owned books
let currBooks = []
//get the index of object I need
let ind = data.map((val, i) => {
if (val.owner === "John Doe") {
currBooks = val.booksOwned
return i
} else {
return -1
}
})
let bookIndex = currBooks.indexOf(newBook)
//insert only if book does not yet exist
if (bookIndex === -1) {
data[ind] = {
owner: "John Doe",
booksOwned: currBooks.push(newBook),
}
setOwnerInfo(data)
}
let data = [...ownerInfo]instead oflet data = ownerInfo.