0

I'm looking for the most concise way to convert an array to an object while plucking the field used as the key for each result.

This is the solution I found, and I'm wondering if there's an easier way.

r.table('product').fold({}, function(products, product) {
  return products.merge(
    r.object(
      product('id').coerceTo('string'),
      product.without('id')
    )
  );
})

Thanks!


Example

// Input:
[{ id: 0, price: 19.99 }, { id: 1, price: 24.99 }]

// Output:
{ "0": { price: 19.99 }, "1": { price: 24.99 } }
aleclarson
  • 18,087
  • 14
  • 64
  • 91

1 Answers1

1

I'm not an expert, but AFAIK, using fold() directly on a table will "stop subsequent commands from being parallelized": https://www.rethinkdb.com/docs/optimization/

So, if I'm not mistaken, if the order is not important it might be better to choose reduce() over fold(), e.g.

table.map(function(row) {
    return r.object(
      row('id').coerceTo('string'), row.without('id')
    )
  })
  .reduce(function(left, right) {
    return left.merge(right)
  })
Kludge
  • 2,653
  • 4
  • 20
  • 42