如何修改数组字段?

Pei*_*ong 6 rethinkdb

假设我有这个对象:

{
    "id":  "1a48c847-4fee-4968-8cfd-5f8369c01f64" ,
    "sections": [
    {
        "id": 0 ,
        "title":  "s1"
    } ,
    {
        "id": 1 ,
        "title":  "s2"
    } ,
    {
        "id": 2 ,
        "title":  "s3"
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

如何直接将第二个标题"s2"更改为其他值?没有加载对象并再次保存?谢谢.

deo*_*ian 8

更新加上changeAt术语:

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"}))
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您已经知道要更改的项目的索引,则上述情况很好.如果需要查找索引,然后更新它,可以使用该.offsetsOf命令查找所需元素的索引:

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"}))
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

编辑:修改后的答案使用 changeAt