How to update a value inside a nested object?
Closed this issue · 1 comments
OziOcb commented
Let's say I have something like this:
{
name: 'Tom',
age: 32,
cars: {
honda: {
year: 2010,
color: 'red'
},
bmw: {
year: 2020,
color: 'black'
}
}
}
Is there a way to update the cars.honda.year
without having to update the entire cars
object??
OziOcb commented
My solution:
methods: {
addOwner() {
db.collection("owners").add(
{
name: "Tom",
age: 32,
cars: {
honda: {
year: 2010,
color: "red",
},
bmw: {
year: 2020,
color: "black",
},
},
},
new Date().toISOString()
);
},
// THE SOLUTION!
async updateOwner(id) {
// Fetch the document from IndexDb using it's ID
const collection = await db.collection("owners").doc(id).get();
// Modify value inside nested object
collection.cars.honda.year = 2021;
// Save the document again
db.collection("owners").doc(id).set(collection);
},
},
(inspired by other IndexDb wrappers)