After assigning data fetched from an API to a variable called todayData
, I noticed that there is a nested object named meals
within it, which contains a property called name
.
My goal is to determine the frequency of occurrences in the name
property within the meals
object.
For instance, the meal Rice
might appear multiple times 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);