以角度计算子对象中变量出现的次数

时间:2019-07-15 13:58:28

标签: javascript angular typescript

我将从API返回的数据分配给名为todayData的变量。有一个名为meals的子对象,其中有一个属性name

我想要实现的是计算name对象的meals属性中出现的次数。 例如,膳食Rice可以在数据中多次出现。

数据

 [{"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);

2 个答案:

答案 0 :(得分:1)

解决方案:

r[row.orders[0].meals[0].name] = ++r[row.orders[0].meals[0].name] || 1;

由于某些属性属于数组类型,因此应设置索引。

编辑1:

具有多个订单和多个餐点的数据的解决方案。 (感谢Bill Cheng让我考虑采用一般方法。)

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);

答案 1 :(得分:1)

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);