[
{
"id":"0001",
"type":"donut",
"name":"Cake",
"ppu":0.55,
"batters":{
"batter":[
{
"id":"1001",
"type":"Regular"
},
{
"id":"1002",
"type":"Chocolate"
}
]
},
"topping":[
{
"id":"5002",
"type":"Glazed"
}
{
"id":"5004",
"type":"Maple"
}
]
},
{
"id":"0002",
"type":"donut",
"name":"Raised",
"ppu":0.55,
"batters":{
"batter":[
{
"id":"1001",
"type":"Regular"
}
]
},
"topping":[
{
"id":"5003",
"type":"Chocolate"
},
{
"id":"5004",
"type":"Maple"
}
]
},
{
"id":"0003",
"type":"donut",
"name":"Old Fashioned",
"ppu":0.55,
"batters":{
"batter":[
{
"id":"1001",
"type":"Regular"
},
{
"id":"1002",
"type":"Chocolate"
}
]
},
"topping":[
{
"id":"5001",
"type":"None"
},
{
"id":"5004",
"type":"Maple"
}
]
}
]
Expected output: [donut, Regular, Chocolate, Glazed, Maple, donut, Regular, Chocolate, Maple, donut, Regular, Chocolate, None, Maple]
Get all values of key(type) from above JSon into an array, including all children. Attached is the sample json and also expected output.
Is there any _lodash function for this or any Javascript function is also fine.
5
Answers
Try this:
BTW, your json object is not in a correct format.
There should be a comma between 5002 and 5004.
Try This:
This is a nice candidate for writing a generator function (and recursion):
I think you need a recursive function for extract all values by key.
There are prebuilt functions in lodash libaray you can use them. Here is the code for the same.
I have used flatmap inside flatmap to maintain the ordering of the output.
if you don’t want to mainatin the order you can use concat function provided by the lodash library.
You can you javascript method to get the desired output.
here jsonArray is your input.