Search code examples
rethinkdbrethinkdb-javascript

RethinkDB generate key-value pair from rows


I have following query which returns the number of request for each status -

r.db.table("request").group("status").count()

result -

[
  {
    "group": "ACCEPTED",
    "reduction": 1
  },
  {
    "group": "DECLINED",
    "reduction": 1
  },
  {
    "group": "PENDING",
    "reduction": 1
  }
]

How can I convert this result to the following using rethinkdb query (javascript)?

{
  "ACCEPTED": 1,
  "DECLINED": 1,
  "PENDING": 1
}

Currently, I am achieving this by iterating the result in api side. But I want this transformation in rethinkdb, if its at all possible?


Solution

  •    r.db("test").table("request").group("status").count()
        .ungroup()
        .map(function(x){ return [x('group'), x('reduction')]; })        
        .coerceTo("object")
    
    • When you want to continue working on your return object you need to call the ungroup() function first
    • Then you need to use the map function to transform your result to:

      [ [ "ACCEPTED" , 1 ] , [ "DECLINED" , 1 ] , [ "PENDING" , 1 ] ]

    • at last you simply transform this to a json-object with coerceTo("object"), which returns you the desired format:

      { "ACCEPTED": 1, "DECLINED": 1, "PENDING": 1 }