0

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'},
  ]);

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

you are So genius

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.