This is my output, what I want is something that I can map with .map()
at the moment I’m not able to map it because there are login and home_page
as key
{
"login": [
{
"id": "clgtg0inx0005sy0llfq2gkvp",
"user_id": "00004",
"project_id": "clgqnhw9u0001syh9rbuvvpkv",
"createdAt": "2023-04-23T13:26:20.541Z",
"updatedAt": "2023-04-23T13:26:20.541Z"
}
],
"home_page": [
{
"id": "clgtewvcw0003sy0lps4i694l",
"user_id": "00004",
"project_id": "clgqnhw9u0001syh9rbuvvpkv",
"createdAt": "2023-04-23T12:55:30.753Z",
"updatedAt": "2023-04-23T12:55:30.753Z"
},
{
"id": "clgtewood0001sy0lgevccham",
"user_id": "00004",
"project_id": "clgqnhw9u0001syh9rbuvvpkv",
"createdAt": "2023-04-23T12:55:22.093Z",
"updatedAt": "2023-04-23T12:55:22.093Z"
}
]
"event_3": [{...}],
"event_4": [{...}],
...
}
Results:
<ul>
<li>login
<ul>
<li>login-info1</li>
</ul>
</li>
<li>home_page
<ul>
<li>home_page-ino1</li>
<li>home_page-ino2</li>
</ul>
</li>
</ul>
where I can expand and see details with below sub array
Let me explain better what i want is an array with a long list of events, and map these inside a UI, but as you can see as key I have the name of the events and the default .map() give me an error events.map is not a function. I need something that I can use to map correctly.
What I did
const reGroup = (list, key) => {
const newGroup = {};
list.forEach(item => {
const newItem = Object.assign({}, item);
delete newItem[key];
newGroup[item[key]] = newGroup[item[key]] || [];
newGroup[item[key]].push(newItem);
});
return newGroup;
};
console.log(reGroup(res.data, 'name'));
setEvents(reGroup(res.data, 'name'))
and
{events?.map((d, i) => {
return <li key={i} className="df-row gap-l">
<InfoInput>{moment(new Date(d.createdAt)).format('MMM D, YYYY hh:mm a')}</InfoInput>
{d.name}
</li>
})}
3
Answers
You just want to merge the object?
Just leverage the rest operator to get what you want.
Let’s call your data object is
source
.Your result object should be
const events = [...source.login, ...source.home_page]
[].concat(...Object.values(data))
orObject.values(data).flat()
(as Thomas has mentioned below) can be used to output a 1D array that contains all the objects in the original object, regardless of which property they were nested under.