I have a json file:
[ { "name": "Cocktail 1", "ingredients": { "rum": 12, "coke": 48 } }, { "name": "Cocktail 2", "ingredients": { "gin": 24, "tonic": 60 } }]
Now I want to get a list of the keys of each “name” object. At the end there should be ths list
var mydata[0] = rum var mydata[1] = coke var mydata[2] = gin var mydata[3] = tonic
and save it into an array.
What i have tried
var mydata = JSON.parse("jsonstring").ingredients;
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())
array.map(a => a.ingredients).map(a => Object.keys(a)).flat();
You may prefer loop style. the only difference is flattening occurs with … operator.
var results = []; for (let a of array) { results.push(...Object.keys(a.ingredients)) }