How do I extract "category" from data and use it as the key for the new output array that includes "name" field from listData array
const data = {
"32": {
"id": 32,
"category": "Grocery Items",
}, I
"33": {
"id": 33,
"category": "Household Items",
},
}
This is the listData array and I would need to extract the data from list.
const listData = [
{
"data": {
"list": [
{
"id": 1,
"category_id": 32,
"title": "Eggs",
"category": "Grocery Items"
},
{
"id": 2,
"category_id": 32,
"title": "Bacon",
"category": "Grocery Items"
}
]
}
}
]
Sample Output:
It contains the category from data as the key and data from list array.
const output = {
"Grocery Items": [
{
"id": 1,
"category": "Grocery Items",
"name": "Eggs",
},
{
"id": 2,
"category": "Grocery Items",
"name": "Bacon",
},
]
}
I tried this but did not give the correct structure
const output = Object.values(data).map((acc, { title, id }) => {
let filteredList = [];
listData.forEach((element) => {
console.log(element.data.list)
filteredList = element.data.list
.filter((item) => item.title === title)
});
if (filteredList.length) {
acc[title] = filteredList;
}
return acc;
}, {});