红颜莎娜
方法一var input = [ { "name": "Siner1", "RTime": 40, "FTime": 30 }, { "name": "Siner2", "RTime": 50, "FTime": 60 }]var output = input.reduce(function(initial,next){ initial["RTime"][next["name"]]=(initial["RTime"][next["name"]] || 0 ) + next["RTime"]; initial["FTime"][next["name"]]=(initial["FTime"][next["name"]] || 0 ) + next["FTime"]; return initial;},{"RTime":{},"FTime":{}});console.log(output)方法二如果您想要聚合其他键或值var input = [ { "name": "Siner1", "RTime": 40, "FTime": 30 }, { "name": "Siner2", "RTime": 50, "FTime": 60 }]var keys = ['RTime','FTime'];output=input.reduce(function(initial,next){ keys.map(function(key){ initial[key][next["name"]]=(initial[key][next["name"]] || 0 ) + next[key]; }); return initial;},keys.reduce(function(data,key){ data[key]={}; return data;},{}));console.log(output)
潇潇雨雨
提供的通用方法基于Array.prototype.reduce. 由于它使用accumulator其回调函数的参数作为可配置项,collector因此它完全不知道任何给定列表的任何已处理项目的键。只需要提供已处理项目的(源)键值,然后作为新分组键值的目标键...function restructureKeysAndValues(collector, item) { const { keyOfTargetValue, registry, index, list } = collector; const targetKey = item[keyOfTargetValue]; Object.entries(item).forEach(([key, value]) => { if (key !== keyOfTargetValue) { let keyGroup = registry[key]; if (!keyGroup) { keyGroup = registry[key] = { [key]: {} }; Object.assign(index, keyGroup); list.push(keyGroup); } keyGroup[key][targetKey] = value; } }); return collector;}console.log('a list of group objects ...', [{ "name": "Siner1", "RTime": 40, "FTime": 30 }, { "name": "Siner2", "RTime": 50, "FTime": 60 }].reduce(restructureKeysAndValues, { keyOfTargetValue: 'name', registry: {}, // - for internal tracking index: {}, // - for external use, output as map/index. list: [] // - for external use, output as array/list. }).list);console.log('a single grouped object ...', [{ "name": "Siner1", "RTime": 40, "FTime": 30 }, { "name": "Siner2", "RTime": 50, "FTime": 60 }].reduce(restructureKeysAndValues, { keyOfTargetValue: 'name', registry: {}, // - for internal tracking index: {}, // - for external use, output as map/index. list: [] // - for external use, output as array/list. }).index);console.log('a list of group objects ...', [{ "name": "Siner1", "RTime": 40, "FTime": 30, "CTime": 70, "ATime": 90 }, { "name": "Siner2", "RTime": 50, "FTime": 60, "CTime": 30, "ATime": 40 }, { "name": "Siner3", "RTime": 90, "FTime": 20, "CTime": 10, "ATime": 20 }].reduce(restructureKeysAndValues, { keyOfTargetValue: 'name', registry: {}, // - for internal tracking index: {}, // - for external use, output as map/index. list: [] // - for external use, output as array/list. }).list);.as-console-wrapper { min-height: 100%!important; top: 0; }