2 回答
TA贡献1780条经验 获得超3个赞
你可以使用reduce
const myObject = [
{ location: 'california', day: 'wednesday', company: 'Tesla' },
{ location: 'washington', day: 'tuesday', company: 'Microsoft' },
{ location: 'california', day: 'wednesday', company: 'Tesla' },
{ location: 'california', day: 'monday', company: 'Apple' },
{ location: 'california', day: 'monday', company: 'SalesForce' },
{ location: 'washington', day: 'tuesday', company: 'Microsoft' },
{ location: 'california', day: 'wednesday', company: 'Apple' }
]
const res = myObject.reduce((acc, obj) => {
const existingIndex = acc.findIndex(
el => el.location === obj.location && el.day === obj.day
)
if (existingIndex > -1) {
acc[existingIndex].count += 1
} else {
acc.push({
location: obj.location,
day: obj.day,
count: 1
})
}
return acc
}, [])
console.log(res)
TA贡献1884条经验 获得超4个赞
你的开始不错。但是,Array.forEach
[ docs ] 返回undefined
(+您实际上是在更新原始对象而不是添加到新对象中)。所以要修复你的开始,你必须做:
var myOutputObject = []; myObject.forEach(function(d) { myOutputObject.push({...d, count: 0}); })console.log(myOutputObject);
让我们制定一个没有二次时间复杂度的解决方案:
const myObject = [
{location: 'california', day: 'wednesday', company: 'Tesla'},
{location: 'washington', day: 'tuesday', company: 'Microsoft'},
{location: 'california', day: 'wednesday', company: 'Tesla'},
{location: 'california', day: 'monday', company: 'Apple'},
{location: 'california', day: 'monday', company: 'SalesForce'},
{location: 'washington', day: 'tuesday', company: 'Microsoft'},
{location: 'california', day: 'wednesday', company: 'Apple'},
];
const m = new Map();
myObject.forEach(({day, location}) => {
// Create a key with values that we want to group by
// A list of key-value pairs is chosen to make use of `Object.fromEntries` later
const hash = JSON.stringify([['day', day], ['location', location]]);
m.set(hash, (m.get(hash) || 0) + 1);
});
const myOutputObject = [...m].map(([rec, count]) => ({
...Object.fromEntries(JSON.parse(rec)),
count,
}))
console.log(JSON.stringify(myOutputObject));
添加回答
举报