Question

In rethinkdb, I'd like to create or modify objects with fields based on a string variable. But rethinkdb does not make a difference between {key: 42} and {"key": 42}, key will always be interpreted as a string literal.

As an example,

r.expr(['a', 'b']).map(function(key) {
  return {key: 42}
})

returns

[{"key":42},{"key":42}]

but I want

[{"a":42},{"b":42}]

The following query does that through manually building a string that represents the object in JSON and then parsing it, but it is quite error-prone and generally does not seem to be the right way to do it.

r.expr(['a', 'b']).map(function(key) {
  return r.json(r.expr('{"').add(key).add('": 42}'))
})

So, is there a good way to prevent rethinkdb from interpreting key as "key"?

Was it helpful?

Solution

You can use coerceTo

r.expr(['a', 'b']).map(function(key) {
  return r.expr([[key, 42]]).coerceTo("OBJECT")
}).run(conn, callback)

The next version (1.12 -- coming this week?) introduced a new term r.object that removes the need for coerceTo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top