javascript - Rethinkdb Array of Object to Object of Array -


i'm trying work rethinkdb in mapreducing like: [{"a":1, "b":2}, {"a":3}, {"c":4}] {"a":[1,3], "b":[2], "c":[4]}.

i have consulted javascript: how convert array of objects object sorted unique arrays? statements doesn't work in reql, here's example:

r.expr([{"a":1, "b":2}, {"a":3}, {"c":4}]).do(function(user){   var c1 = {};     var keys = ["a", "b", "c"];            user.map(function(itm){       keys.map(function(p){         if(!c1[p]){           c1[p] = [];         };         c1[p] = r.expr(c1[p]).setinsert(itm(p).default("nil"));       });       return 1     });   return c1 }); 

but faults out on itm(p) error: rqlcompileerror: variable name not found in:

rqlcompileerror: variable name not found in:  r([{a: 1, b: 2}, {a: 3}, {c: 4}]).do(function(var_136) { return {a: r([]).setinsert(var_137("a").default("nil")), b: r([]).setinsert(var_137("b").default("nil")), c: r([]).setinsert(var_137("c").default("nil"))}; })                                                                                      ^^^^^^^                                                                                                                            

because rethinkdb assigning variable id (137 in case) itm(p) that's not declared beforehand.

any ideas how can this?

thanks

adapting answer danielmewes on github

var input = r.expr([{"a":1}, {"a":3}, {b: 2}, {"a":4}, {b: 3}]); var keys = input.map(function(x){return x.keys()})   .reduce(function(l, r){return l.setunion(r)});   .map(function(key){ return [key, input(key)]})   .coerceto('object'); 

since uses advanced reql techniques, here's how breaks down:

  1. first grab keys of every object in array. results in array of arrays
  2. next reduce, pairwise combination of elements previous array of arrays. end deduplicated list of keys in of objects in original array.
  3. next, each key, create 2 element array first element key, , second element array of of values in original input key.
    • this works because () in reql more powerful regular javascript [] brackets. collect values of field key.
    • the output of step array of arrays [['a', [1,2]], ['b', [3,4]]
  4. finally, coerce object. reql can coerce arrays [['a', 1], ['b', 2]] object {a: 1, b: 2}, useful here.

Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -