to_dictionary
TABLE OF CONTENTS
Convert an array into an object with a specific structure
Definition
object to_dictionary(array[any] $array, expression->string $keyExpression, expression->any $valueExpression)
Converts $array into an object. Evaluates $keyExpression against the $array elements, and each unique result of a $keyExpression yields a key. The value is an array whose elements are the evaluations of $valueExpression on the elements that yield the same result upon evaluating the $keyExpression.
Parameters
array[any] $array
Array to convert to object.
expression->string $keyExpression
Expression defining the keys of the new dictionary.
expression->any $valueExpression
Expression defining the values in the array assigned to keys resulting from $keyExpression
Returns
object
Object where the keys are the results of evaluating $keyExpression against $array elements, and values equal to arrays of results of applying $valueExpression to the elements with equal $keyExpression values. For elements where $keyExpression evaluates to null, the default key name is _.
Examples
{
"simpleArray": [1, 2, 3],
"objectArray": [
{
"Region": "Germany",
"Product": "Apple",
"Units": "51"
},
{
"Region": "Denmark",
"Product": "Apple",
"Units": "99"
},
{
"Region": "Germany",
"Product": "Orange",
"Units": "66"
},
{
"Product": "Apple",
"Units": "51"
}
]
}{
a: to_dictionary(simpleArray, join('', ['key', to_string(@)]), @),
b: to_dictionary(objectArray, &Region, &@.Product)
}{
"a": {
"key1": [1],
"key2": [2],
"key3": [3]
},
"b": {
"Germany": ["Apple", "Orange"],
"Denmark": ["Apple"],
"_": ["Apple"]
}
}Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article