获取元素,删除重复项并计算每个

时间:2018-05-31 12:30:16

标签: javascript angular typescript

我有以下列表(对象):

var data = [{
    id: 1,
    type: 'smartphone',
    details: [{
      brand: 'Samsung',
      model: 'Galaxy A5'
    }]
  },
  {
    id: 2,
    type: 'smartphone',
    details: [{
      brand: 'iPhone',
      model: '6 plus'
    }]
  },
  {
    id: 3,
    type: 'smartphone',
    details: [{
      brand: 'Samsung',
      model: 'Galaxy A5'
    }]
  },
  {
    id: 4,
    type: 'smartphone',
    details: [{
      brand: 'iPhone',
      model: '7 plus'
    }]
  },
  {
    id: 5,
    type: 'phone',
    details: [{
      brand: 'Nokia',
      model: '3310'
    }]
  },
  {
    id: 6,
    type: 'smartphone',
    details: [{
      brand: 'Samsung',
      model: 'Galaxy A5'
    }]
  },
  {
    id: 7,
    type: 'smartphone',
    details: [{
      brand: 'iPhone',
      model: '6 plus'
    }]
  }
]

我尝试在页面上显示已过滤的手机列表以及使用javascript / angular的总金额

所以在我的页面上我想要以下结果:

  

手机:三星,型号:Galaxy A5,总计:3

     

手机:iPhone,型号:7加,总计:1

     

手机:iPhone,型号:6加,总计:2

     

电话:诺基亚,型号:3310,总计:1

我将使用ngFor渲染它,但不太确定如何同时过滤和计算每个模型的总数。 提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用reduce()方法将数据转换为一个对象或一组对象,并计算每个模型和品牌的总数。

var data = [{"id":1,"type":"smartphone","details":[{"brand":"Samsung","model":"Galaxy A5"}]},{"id":2,"type":"smartphone","details":[{"brand":"iPhone","model":"6 plus"}]},{"id":3,"type":"smartphone","details":[{"brand":"Samsung","model":"Galaxy A5"}]},{"id":4,"type":"smartphone","details":[{"brand":"iPhone","model":"7 plus"}]},{"id":5,"type":"phone","details":[{"brand":"Nokia","model":"3310"}]},{"id":6,"type":"smartphone","details":[{"brand":"Samsung","model":"Galaxy A5"}]},{"id":7,"type":"smartphone","details":[{"brand":"iPhone","model":"6 plus"}]}]

var result = data.reduce((r, {details}) => {
  details.forEach(({brand, model}) => {
    let key = `${brand}|${model}`;
    if(!r[key]) r[key] = {phone: brand, model, total: 0}
    r[key].total++;
  })
  return r;
}, {})

console.log(Object.values(result))

答案 1 :(得分:1)

您可以使用reduce删除重复项..

.NET Core 2.1