-
富国沪深
使用Array.reduce()var sample= [ { Name: 'Poorna', Amount: 50}, { Name: 'Kumar', Amount: 50}, { Name: 'Ashok ', Amount: 75}, { Name: 'Poorna', Amount: 35}, ];var res = sample.reduce((a, obj)=>{ var existItem = a.find(item => item.Name=== obj.Name); if(existItem){ existItem.Amount += obj.Amount; return a; } a.push(obj); return a;}, []);console.log(res);
-
慕码人2483693
您可以使用地图来做到这一点:import React from "react";export default function App() { const list = [ { name: 'Poorna', amount: 11000 }, { name: 'Kumar', amount: 2900 }, { name: 'Ashok', amount: 20000 }, { name: 'Kumar', amount: 3020 }, { name: 'Poorna', amount: 15000 } ]; const map = new Map(); list.forEach(({ name, amount }) => map.set(name, map.has(name) ? map.get(name) + amount : amount)); const listItems = [...map.entries()].map(([name, amount]) => <li>{name}: {amount}</li>); return <ul>{listItems}</ul>;}
-
繁星淼淼
我认为下面是最好的方法。const data = [ { Name: 'Poorna', Amount: 11000 }, { Name: 'Kumar', Amount: 2900 }, { Name: 'Ashok', Amount: 20000 }, { Name: 'Kumar', Amount: 3020 }, { Name: 'Poorna', Amount: 15000 },];const result = data.reduce((prev, { Name, Amount }) => { if (prev[Name]) return {...prev, [Name]: prev[Name] + Amount}; return {...prev, [Name]: Amount};}, {});
-
慕桂英546537
这是根据名称对数据进行分组的方法:let data = [ {name: "Poorna", salary:11000.0}, {name: "Kumar",salary: 2900.0}, {name: "Ashok", salary:20000.0}, {name: "Kumar", salary:3020.0}, {name: "Poorna", salary:15000.0},];let sol = {};for (let a of data) { if (sol[a.name]) {sol[a.name] += a.salary; } else {sol[a.name] = a.salary; }}console.log(sol);这是完整的反应应用程序:import React, { useState, useEffect } from "react";import "./style.css";let data = [ { name: "Poorna", salary: 11000.0 }, { name: "Kumar", salary: 2900.0 }, { name: "Ashok", salary: 20000.0 }, { name: "Kumar", salary: 3020.0 }, { name: "Poorna", salary: 15000.0 }];export default function App() { const [initialData, setInitialData] = useState(data); const [group, setGroup] = useState([]); const groupData = () => { let sol = {}; for (let a of initialData) { if (sol[a.name]) { sol[a.name] += a.salary; } else { sol[a.name] = a.salary; } } setGroup(sol); }; useEffect(() => { groupData(); }, []); return ( <div> <table> <tr> {" "} <th>Name</th> <th>Amount</th> </tr> {initialData.map(d => ( <tr> {" "} <td>{d.name}</td> <td>{d.salary}</td> </tr> ))} </table> <h2>Grouped data</h2> <table> <tr> <th>Name</th> <th>Amount</th> </tr> {group && Object.keys(group).map(key => ( <tr> <td>{key}</td> <td>{group[key]}</td> </tr> ))} </table> </div> );}您可以在这里找到工作应用程序:Stackblitz Link
-
九州编程
使用reduce()const array = [{ id: 1, name: 'Poorna', amount: 11000 }, { id: 2, name: 'Kumar', amount: 2900}, { id: 3, name: 'Ashok', amount: 20000},{ id: 3, name: 'Kumar', amount: 3020},{ id: 3, name: 'Poorna', amount: 15000}]; let output = Object.values(array.reduce((acc, curr) => { if (acc[curr.name]) acc[curr.name].amount += curr.amount; else acc[curr.name] = { ...curr }; return acc; }, {}));console.log(output);