-
侃侃尔雅
就像您提到的那样,我们可以使用对象而不是数组作为最外层的包装器。并且还将一个对象内部交换为数组,那么这是一种可能的解决方案。var data = [{"name": "JOHN","type": 1,"sum": 5},{"name": "SERA","type": 1,"sum": 43},{"name": "SERA","type": 2,"sum": 129},{"name": "JOHN","type": 2,"sum": 200}];var newData = {};data.forEach( (item) => { if (!(item['name'] in newData)) { newData[item['name']] = []; } newData[item['name']].push( { 'type': item['type'], 'sum' : item['sum'] } );});console.log(newData);
-
心有法竹
您建议的输出结构无效,但是使用Array.reduce您可以创建一个对象,其中所有属性都是对象数组:const data = [ { "name": "JOHN", "type": 1, "sum": 5 }, { "name": "SERA", "type": 1, "sum": 43 }, { "name": "SERA", "type": 2, "sum": 129 }, { "name": "JOHN", "type": 2, "sum": 200 }];const result = data.reduce((c, {name, type, sum}) => { c[name] = c[name] || []; c[name].push({type, sum}); return c;}, {});console.log(result);
-
慕运维8079593
forEach使用,destructuring和??运算符的另一种方式const merge = (arr) => { const obj = {}; arr.forEach(({ name, ...rest }) => (obj[name] ??= []).push(rest)); return obj;};const data = [ { name: "JOHN", type: 1, sum: 5, }, { name: "SERA", type: 1, sum: 43, }, { name: "SERA", type: 2, sum: 129, }, { name: "JOHN", type: 2, sum: 200, },];console.log(merge(data));
-
胡说叔叔
您可以使用此函数将 Array.prototype.reduce初始数据转换为另一种数组结构。let data = [ { "name": "JOHN", "type": 1, "sum": 5 }, { "name": "SERA", "type": 1, "sum": 43 }, { "name": "SERA", "type": 2, "sum": 129 }, { "name": "JOHN", "type": 2, "sum": 200 }];function groupedBy(data, field) { let fieldValues = [...data].reduce((acc, current) => { return acc.concat(current[field]); }, []).filter((value, index, self) => { return self.indexOf(value) === index; }); let results = fieldValues.reduce((acc, item) => { let items = [...data].filter(el => { return el.name === item; }); items.forEach(i => delete i.name); return Object.assign(acc, { [item]: items}); }, {}); return results;}console.log(groupedBy(data, "name"));