House3272 House3272 - 1 month ago 6
Javascript Question

How to update an array of objects?

For example,

{
id:"monday",
names:[
{one:"white", two:"pink"},
{uno:"blanco", dos:"rosado"}
]
}


How would you change
white
to
black
?

So far, I've got this:

r.db.table.get('monday').update({
names: r.row("names").nth(0)
})


Which specifies the 0th index of
names
, but not sure how to further specify the
one
field and then change it.

Answer

What you have so far is pretty correct but you replace names with its first sub-object (I guess you saw that result already).

You just need to use a merge to alter the sub-object, and a changeAt on names to put the altered sub-object in the array, just like this:

r.db.table.get('monday').update({
  names: r.row('names').changeAt(0, r.row('names').nth(0).merge({one: 'black'}))
})

Hope this helps!