2 回答

TA貢獻1780條經驗 獲得超4個贊
你可以使用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));
添加回答
舉報