When I try to use $value
as the 2nd parameter to the toKeyedObject
formatter, I’m getting an object with undefined
values.
Is it expected or is it a bug?
Given this array:
dmx.app.set('arr', [{k:'a', v:1}, {k:'b', v:2}, {k:'c', v:3}])
when I want to turn it into a lookup table (aka map, hash-map, object, dictionary)
dmx.parse("arr.toKeyedObject('k', '$value')")
I get
{a: undefined, b: undefined, c: undefined}
but I was expecting
{a: {k:'a', v:1}, b: {k:'b', v:2}, c: {k:'c', v:3}}
since
dmx.parse("arr.map('v')")
[1, 2, 3]
dmx.parse("arr.map('$value')")
[{k:'a', v:1}, {k:'b', v:2}, {k:'c', v:3}]
and
dmx.parse("arr.toKeyedObject('k', 'v')")
{a: 1, b: 2, c: 3}
groupBy
almost yields what I expect, but the values are wrapped into an undesired array (since we know that values of k
is unique, by definition):
dmx.parse("arr.groupBy('k')")
{a: [{k:'a', v:1}], b: [{k:'b', v:2}], c: [{k:'c', v:3}]}
Here is a custom formatter just for this purpose (based on the implementation of groupBy
), but I have the feeling, that toKeyedObject
should already provide this behaviour:
dmx.Formatter('array', 'indexBy', function (arr, key_expr) {
const scope = this, key_is_prop = dmx.propCheck.test(key_expr)
return arr.reduce(
(o, item) => {
const key = key_is_prop
? item[key_expr]
: dmx.parse(key_expr, new dmx.DataScope(item, scope))
o[key] = item
return o
}, {})
})