如何从对象中获取值作为数组
How to get values from object as an array
我们需要将对象转换为对象数组并在字段上进行映射,但字段是增量的,如 field1、field2,这就是我们遇到的问题。
我尝试了以下代码:
output application/json
---
payload.main.field map(value) -> {
"name": value.name,
"age": value.age,
"location": value.location[0].country
}
输入:
{
"main": {
"field1": {
"name": "value",
"age": 20,
"address": {
"location": [
{
"country": "US",
"zipcode": 1234
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field2": {
"name": "pqr",
"age": 23,
"address": {
"location": [
{
"country": "CA",
"zipcode": 1235
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field3": {
"name": "abc",
"age": 22,
"address": {
"location": [
{
"country": "BU",
"zipcode": 1236
},
{
"country": "US",
"zipcode": 1234
}
]
}
}
}
}
对于上面的输入,下面是预期的响应。
预期输出:
{
"main": [
{
"name": "value",
"age": 20
"location": "US"
},
{
"name": "pqr",
"age": 23
"location": "CA"
},
{
"name": "abc",
"age": 22
"location": "BU"
}
]
}
对于location,当数组大小不为0且country不为null时,就像location[0].country。
output application/json
---
main : payload.main pluck $ map {
"name": $.name,
"age": $.age,
"location": if( sizeOf($.address.location) !=0) $.address.location[0].country else "N/A"
}
我们需要将对象转换为对象数组并在字段上进行映射,但字段是增量的,如 field1、field2,这就是我们遇到的问题。 我尝试了以下代码:
output application/json
---
payload.main.field map(value) -> {
"name": value.name,
"age": value.age,
"location": value.location[0].country
}
输入:
{
"main": {
"field1": {
"name": "value",
"age": 20,
"address": {
"location": [
{
"country": "US",
"zipcode": 1234
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field2": {
"name": "pqr",
"age": 23,
"address": {
"location": [
{
"country": "CA",
"zipcode": 1235
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field3": {
"name": "abc",
"age": 22,
"address": {
"location": [
{
"country": "BU",
"zipcode": 1236
},
{
"country": "US",
"zipcode": 1234
}
]
}
}
}
}
对于上面的输入,下面是预期的响应。
预期输出:
{
"main": [
{
"name": "value",
"age": 20
"location": "US"
},
{
"name": "pqr",
"age": 23
"location": "CA"
},
{
"name": "abc",
"age": 22
"location": "BU"
}
]
}
对于location,当数组大小不为0且country不为null时,就像location[0].country。
output application/json
---
main : payload.main pluck $ map {
"name": $.name,
"age": $.age,
"location": if( sizeOf($.address.location) !=0) $.address.location[0].country else "N/A"
}