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

时间:2019-02-04 05:06:54

标签: javascript lodash

在javascript中,我有一个看起来像这样的对象数组

[{符号:“ SYM”,值:1},{符号:“ SYM”,值:1},{符号:“ DOG”,值:2}]

  

[{符号:“ SYM”,值:1},{符号:“ SYM”,值:1},{符号:“ DOG”,值:2}]

如何将其缩小为

  

[{符号:“ SYM”,值:2},{符号:“ DOG”,值:2}]

即总结匹配符号的值

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用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++
  } else {
    out[inp.symbol] = inp
  }
  return out
},{})


console.log(Object.values(op))

答案 2 :(得分:0)

您可以使用lodash的_.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>