ObjectToArray (NoSQL query)
APPLIES TO: NoSQL
Converts each field/value pair in a JSON object into an element and then returns the set of elements as a JSON array. By default, the array elements contain a new k
field for the original field's name and a new v
field for the original field's value. These new field names can be further customized.
Syntax
ObjectToArray(<object_expr> [, <string_expr_1>, <string_expr_2>])
Arguments
Description | |
---|---|
object_expr |
An object expression with properties in field/value pairs. |
string_expr_1 (Optional) |
A string expression with a name for the field representing the field portion of the original field/value pair. |
string_expr_2 (Optional) |
A string expression with a name for the field representing the value portion of the original field/value pair. |
Return types
An array of elements with two fields, either k
and v
or custom-named fields.
Examples
This example demonstrates converting a static object to an array of field/value pairs using the default k
and v
identifiers.
SELECT VALUE
ObjectToArray({
"a": "12345",
"b": "67890"
})
[
[
{
"k": "a",
"v": "12345"
},
{
"k": "b",
"v": "67890"
}
]
]
In this example, the field name is updated to use the name
identifier.
SELECT VALUE
ObjectToArray({
"a": "12345",
"b": "67890"
}, "name")
[
[
{
"name": "a",
"v": "12345"
},
{
"name": "b",
"v": "67890"
}
]
]
In this example, the value name is updated to use the value
identifier and the field name uses the key
identifier.
SELECT VALUE
ObjectToArray({
"a": "12345",
"b": "67890"
}, "key", "value")
[
[
{
"key": "a",
"value": "12345"
},
{
"key": "b",
"value": "67890"
}
]
]
This final example uses an item within an existing container that stores data using fields within a JSON object.
[
{
"name": "Witalica helmet",
"quantities": {
"small": 15,
"medium": 24,
"large": 2,
"xlarge": 0
}
}
]
In this example, the function is used to break up the object into an array item for each field/value pair.
SELECT
p.name,
ObjectToArray(p.quantities, "size", "quantity") AS quantitiesBySize
FROM
products p
WHERE
p.category = "sport-helmets"
[
{
"name": "Witalica helmet",
"quantitiesBySize": [
{
"size": "small",
"quantity": 15
},
{
"size": "medium",
"quantity": 24
},
{
"size": "large",
"quantity": 2
},
{
"size": "xlarge",
"quantity": 0
}
]
}
]
Remarks
- If the input value isn't a valid object, the result is
undefined
.