Reputation: 193
I want to create a new object by adding count
values of keys with the same name
and then merge them.
I could use filter
and map
but that's for the case that I already know
what keys
would be inside of the object. like below.
obArr.filter(v => v.site === 'jelly').map(...);
but it needs lot of works (lot of filter
and map
for each key
) and
key
name would be vary each time.
In this case what could be the better way?
This is the data and desired result below.
const obArr = [{site: "candy", date: "2021-04-30", count: 10},
{site: "jelly", date: "2021-04-30", count: 2},
{site: "candy", date: "2021-04-29", count: 12},
{site: "jelly", date: "2021-04-29", count: 3},
{site: "candy", date: "2021-04-29", count: 5},
{site: "chocolate", date: "2021-04-29", count: 9},
{site: "jelly", date: "2021-04-29", count: 20},
{site: "chocolate", date: "2021-04-29", count: 21}];
//desired result
const [state, setState] = useState([
{site: 'candy', count: 27},
{site: 'chocolate', count: 30},
{site: 'jelly', count: '25'},
]);
Upvotes: 0
Views: 31
Reputation: 371168
Count up the number of counts
on an object (or Map) instead while iterating over the array:
const obArr = [{site: "candy", date: "2021-04-30", count: 10},
{site: "jelly", date: "2021-04-30", count: 2},
{site: "candy", date: "2021-04-29", count: 12},
{site: "jelly", date: "2021-04-29", count: 3},
{site: "candy", date: "2021-04-29", count: 5},
{site: "chocolate", date: "2021-04-29", count: 9},
{site: "jelly", date: "2021-04-29", count: 20},
{site: "chocolate", date: "2021-04-29", count: 21}];
const grouped = {};
for (const { site, count } of obArr) {
grouped[site] = (grouped[site] || 0) + count;
}
const initialState = Object.entries(grouped).map(([site, count]) => ({ site, count }));
console.log(initialState);
// const [state, setState] = useState(initialState);
Upvotes: 1