How can I modify array fields in place?
Asked Answered
L

1

6

Let's say I have this object:

{
    "id":  "1a48c847-4fee-4968-8cfd-5f8369c01f64" ,
    "sections": [
    {
        "id": 0 ,
        "title":  "s1"
    } ,
    {
        "id": 1 ,
        "title":  "s2"
    } ,
    {
        "id": 2 ,
        "title":  "s3"
    }
    ]
}

How can I directly change 2nd title "s2" to other value? without loading the object and save again? Thanks.

Languet answered 16/12, 2014 at 15:48 Comment(5)
Do you want to do this update in ReQL or something else? Please be more specific.Metaphrast
using javascript api. ReQL or not doesn't matter if it works. : )Languet
It matters if there are over 20 different languages it supportsMetaphrast
Have you looked at the documentation? http://rethinkdb.com/api/javascript/#updateMetaphrast
The examples only shows update root fields or non-array fields and it works. but when I try row.array[i].property = value, it doesn't work. that's why I want a solution.Languet
B
9

Update plus the changeAt term:

r.table('blog').get("1a48c847-4fee-4968-8cfd-5f8369c01f64").update(function(row){
  return {
    sections: row('sections').changeAt(1,
        row('sections')(1).merge({title: "s2-modified"}))
  }
}

The above is good if you already know the index of the item you want to change. If you need to find the index, then update it, you can use the .offsetsOf command to look up the index of the element you want:

r.table('table').get("1a48c847-4fee-4968-8cfd-5f8369c01f64").update(function(row){
  return row('sections').offsetsOf(function(x){
    return x('title').eq('s2')
  })(0).do(function(index){
    return {
        sections: row('sections').changeAt(index,
           row('sections')(index).merge({title: "s2-modified"}))
    }
  })
})

Edit: modified answer to use changeAt

Barbados answered 16/12, 2014 at 22:21 Comment(2)
Please not that indexesOf is nowadays called offsetsOf.Sweptwing
@MikaelLirbank fixed! Thanks.Barbados

© 2022 - 2024 — McMap. All rights reserved.