Reputation: 19035
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!
// Input:
[{ id: 0, price: 19.99 }, { id: 1, price: 24.99 }]
// Output:
{ "0": { price: 19.99 }, "1": { price: 24.99 } }
Upvotes: 0
Views: 42
Reputation: 2835
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)
})
Upvotes: 1