可以使用JavaScript中的reduce和map方法来解决此问题。假设原始数据数组为data,其中每个对象都有一个id和amount字段和其他可能包含字符串的字段。以下是示例代码:
const data = [ { id: 1, amount: 100, name: 'John' }, { id: 2, amount: 200, address: '123 Main St' }, { id: 1, amount: 50, email: 'john@example.com' }, { id: 3, amount: 300, phone: '555-1234' }, { id: 2, amount: 150, occupation: 'Developer' }, ];
const result = Object.values(data.reduce((acc, { id, amount, ...rest }) => { if (!acc[id]) acc[id] = { id, total: 0, strings: [] }; acc[id].total += amount; acc[id].strings.push(...Object.values(rest).filter(val => typeof val === 'string')); return acc; }, {}));
console.log(result);
在这个例子中,reduce方法用于按id将对象数组分组,并将每个对象的amount字段总和和所有字符串元素推入数组。接着,使用Object.values方法将累加器对象转为数组形式并将其存储在变量result中。最后,输出结果。该示例代码的输出结果如下所示:
[ { id: 1, total: 150, strings: [ 'John', 'john@example.com' ] }, { id: 2, total: 350, strings: [ '123 Main St', 'Developer' ] }, { id: 3, total: 300, strings: [ '555-1234' ] } ]