代码之家  ›  专栏  ›  技术社区  ›  jcgh582

对象列表中匹配属性的汇总属性

  •  -1
  • jcgh582  · 技术社区  · 5 年前

    [{symbol: "SYM", value: 1}, {symbol: "SYM", value: 1}, {symbol: "DOG", value: 2}]
    

    我该怎么减少

    [{symbol: "SYM", value: 2}, {symbol: "DOG", value: 2}]
    

    一、 e.总结匹配符号的值

    3 回复  |  直到 5 年前
        1
  •  0
  •   Dhananjai Pai    5 年前
    let arr = [{symbol: "SYM", value: 1}, {symbol: "SYM", value: 1}, {symbol: "DOG", value: 2}];
    valMap = arr.reduce((acc,val) => {
        if(!acc[val.symbol]) acc[val.symbol]=val.value;
        else acc[val.symbol] += val.value;
        return acc;
    } ,{});
    const result = Object.keys(valMap).map(key => ({symbol:key, value:valMap[key]}));
    
        2
  •  0
  •   Ori Drori    5 年前

    你可以用洛达斯的 _.groupBy() _.sumBy()

    const fn = _.flow(
      arr => _.groupBy(arr, 'symbol'),
      groups => _.map(groups, g => 
        _.assign({}, _.head(g), { value: _.sumBy(g, 'value') })
      )
    );
    
    const arr = [{symbol: "SYM", value: 1}, {symbol: "SYM", value: 1}, {symbol: "DOG", value: 2}]
    
    const result = fn(arr);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
        3
  •  0
  •   Code Maniac    5 年前

    你可以用 reduce

    let obj = [{symbol: "SYM", value: 1}, {symbol: "SYM", value: 1}, {symbol: "DOG", value: 2}]
    
    let op = obj.reduce((out,inp)=>{
      if(out[inp.symbol]){
        out[inp.symbol].value+= inp.value
      } else {
        out[inp.symbol] = inp
      }
      return out
    },{})
    
    
    console.log(Object.values(op))