How can I modify array fields in place?

微笑、不失礼 提交于 2019-12-06 01:43:23

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/27508480/how-can-i-modify-array-fields-in-place

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!