在javascript中,我有一个看起来像这样的对象数组
[{符号:“ SYM”,值:1},{符号:“ SYM”,值:1},{符号:“ DOG”,值:2}]
[{符号:“ SYM”,值:1},{符号:“ SYM”,值:1},{符号:“ DOG”,值:2}]
如何将其缩小为
[{符号:“ SYM”,值:2},{符号:“ DOG”,值:2}]
即总结匹配符号的值
答案 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>