I am trying to loop through my JSON data and form an array of objects. I am counting the number of fruits in each State.
My JSON data is as below:
const data =
[
{
“State”: “California”, “Fruits”: [{"name": “oranges”, "code": “112”}, {"name": “apple, "code": “111”}]
},
{
“State”: “Arizona”, “Fruits”: [{"name": “oranges”, "code": “112”}, {"name": “apple, "code": “111”}, {"name": “kiwi, "code": “999”}]
},
{
“State”: “Ohio”, “Fruits”: [{"name": “oranges”, "code": “112”}, {"name": “kiwi, "code": “999”}]
},
{
“State”: “Arizona”, “Fruits”: [{"name": “kiwi, "code": “999”}]
},
{
“State”: “California”, “Fruits”: [{"name": “oranges”, "code": “112”}, {"name": “apple, "code": “111”}, {"name": “kiwi, "code": “999”}]
},
{
“State”: “Arizona”, “Fruits”: [{"name": “oranges”, "code": “112”}, {"name": “apple, "code": “111”}]
},
]
My desired output is as below:
[
{
State: ‘California’,
Fruits: [
{ name: 'Apples', count: 2 },
{ name: 'Oranges', count: 2 },
{ name: 'Kiwi', count: 1 }
]
},
{
State: ‘Arizona’,
Fruits: [
{ name: 'Apples', count: 2 },
{ name: 'Oranges', count: 2 },
{ name: 'Kiwi', count: 2 }
]
},
{
State: ‘Ohio’,
Fruits: [
{ name: 'Oranges', count: 1 },
{ name: 'Kiwi', count: 1 }
]
}
];
When i loop through the JSON data and count the fruits i am unable to get it in the desired format. below is my code:
let obj = {}
for(let i=0; i<data.length; i++){
for(let j=0; j<data[i].fruits.length; j++){
obj[data[i].fruits[j].name]? obj[data[i].fruits[j].name]++ : obj[data[i].fruits[j].name]=1;
}
}
The above loop gives the output as:
{
"Apples" : 4,
"Oranges": 5,
"kiwi": 4
}
How do i change my loop to get my desired format??
2
Answers
You can first group all the fruits by state, then use
Array#reduce
to count in each state.You can try this: