I have a json file:
JavaScript
x
15
15
1
[
2
{
3
"name": "Cocktail 1",
4
"ingredients": {
5
"rum": 12,
6
"coke": 48
7
}
8
}, {
9
"name": "Cocktail 2",
10
"ingredients": {
11
"gin": 24,
12
"tonic": 60
13
}
14
}]
15
Now I want to get a list of the keys of each “name” object. At the end there should be ths list
JavaScript
1
5
1
var mydata[0] = rum
2
var mydata[1] = coke
3
var mydata[2] = gin
4
var mydata[3] = tonic
5
and save it into an array.
What i have tried
JavaScript
1
2
1
var mydata = JSON.parse("jsonstring").ingredients;
2
hope this is understanable?
Advertisement
Answer
for each data in the array (map) you want the ingredient part (.ingredients), extract the keys (Object.keys) and flatten the array (.flat())
JavaScript
1
2
1
array.map(a => a.ingredients).map(a => Object.keys(a)).flat();
2
You may prefer loop style. the only difference is flattening occurs with … operator.
JavaScript
1
5
1
var results = [];
2
for (let a of array) {
3
results.push(Object.keys(a.ingredients))
4
}
5