Get specific object field with condition and make opertion on it

I have objects like this:

{
   buildings: {
       "1": {
         "l": 0 ,
         "r": 0 ,
         "s": 0 ,
         "type": "GoldMine" ,
         "x": 2 ,
         "y": 15
       } ,
       "10": {
         "l": 0 ,
         "r": 6 ,
         "s": 2 ,
         "type": "MagicMine" ,
         "x": 26 ,
         "y": 22
       } 
  } ,
  [...] 
}

I want to get objects with buildings of type "GoldMine".

I tried something with map:

r.table("Characters").map(function(row) {
  return row("planet")("buildings")
})

With keys() I can iterate it:

r.db("Unnyworld").table("Characters").map(function(row) {
    return row("planet")("buildings").keys().map(function(key) {
       return  "need to get only buildings with type == GoldMine";
    })
}).limit(2)

But it returns all buildings. I want to get only buildings with type == GoldMine and change field x.

Upvotes: 0

Views: 51

Answers (1)

kureikain
kureikain

Reputation: 2314

Something like this may work:

r.table('Characters')
  .concatMap(function(doc) {
    return doc("planet")("buildings").keys().map(function(k) {
      return {id: doc('id'), key: k, type: doc("planet")("buildings")(k)('type'), x: doc("planet")("buildings")(k)('x')}
    })
  })

  .filter(function(building) {
    return building('type').eq('GoldMine')
  })

  .forEach(function(doc) {
    return r.table('Characters').get(doc('id'))
      .update({
        planet: {buildings: r.object(doc('key'), {x: 1111111})}
        })
  })

Basically create a flat array from building by using concatMap then filter it. With result data, we can iterator over it and update to value that we want.

Upvotes: 1

Related Questions