Reputation: 49
I assigned a data that is returned from an API to a variable named todayData
. There's a child object called meals
which in it has a property name
.
What I want to achieve is to count the number of occurrences in the name
property of the meals
object.
For example, the meal Rice
can have multiple occurrences in the data.
DATA
[{"id":5,"referenceId":1189,"firstName":"Dan","lastName":"Daniels","orders":[{"id":109,"meals":[{"id":47,"name":"Fried Rice","description":"This is a very sweet meal","image":"","mealType":"LUNCH","unitPrice":-20,"status":"ENABLED"}],"serveDate":"2019-07-11 00:00:00"}]}]
JS
let occurences = this.todayData.reduce(function (r, row) {
r[row.orders.meals.name] = ++r[row.orders.meals.name] || 1;
return r;
}, {});
let result = Object.keys(occurences).map(function (key) {
return { meals: key, count: occurences[key] };
});
console.log(result);
Upvotes: 1
Views: 153
Reputation: 2809
SOLUTION:
r[row.orders[0].meals[0].name] = ++r[row.orders[0].meals[0].name] || 1;
Since some properties are of Array type, index should be set.
EDIT 1:
Solution for data with multiple orders along with multiple meals. (Thanks to Bill Cheng for making me to consider general approach.)
let mealOccureneceCount = {};
let occurences = this.todayData.forEach(user => {
user.orders.forEach(order => {
order.meals.forEach(meal => {
mealOccureneceCount[meal.name] = (mealOccureneceCount[meal.name] || 0) + 1;
});
});
});
console.log(mealOccureneceCount);
Upvotes: 1
Reputation: 956
const occurences = this.todayData.reduce((r1, c1) => c1.orders.reduce((r2,c2) => c2.meals.reduce((r3,c3) => { r3[c3.name]= (r3[c3.name] || 0) + 1; return r3;}, r2), r1),{});
const result = Object.entries(occurences).map(([key, value]) => ({ meals: key, count: value }));
console.log(result);
Upvotes: 1