I am new to react js, I searched google, object append, object concatenation, shallow copy, a deep copy are there in JavaScript, But, I can't find out the merge the array of objects into a single array of objects.
How to filter an array of objects based on the type and save the response as a single array of objects?
const options = ["Fruit", "Vegitables", "Drinks"];
const mainArray=[{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Vegitables',
Name:'tomoto',
Amount:'50'
},
{
Type:'Vegitables',
Name:'onion',
Amount:'20'
},
{
Type:'Drinks',
Name:'Milk',
Amount:'30'
},
{
Type:'Drinks',
Name:'Juice',
Amount:'20'
}
]
///Filtering By Type
const filterByType=()=>{
let allMergedData=[];
selectedtypes?.map((type)=>{
let mergedData=[];
let filteredData= mainArray?.filter(x=>x.Type===type.toLowerCase());
mergedData=[...filteredData];
allMergedData=[...mergedData, ...filteredData];
})
return allMergedData;
};
return(
<div>
{options.map((option) => (
<MenuItem key={option} value={name}>
<Checkbox value={option}
onChange={handleChange}
checked={selected.includes(option)} />
<ListItemText primary={option} />
</MenuItem>
))}
</div>
)
Excepted output:
allMergedData:[{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Vegitables',
Name:'tomoto',
Amount:'50'
},
{
Type:'Vegitables',
Name:'onion',
Amount:'20'
},]
```
Maybe this function could help, edited as your need:
function groupBy(arr, criteria) {
const newObj = arr.reduce(function (acc, currentValue) {
if (!acc[currentValue[criteria]]) {
acc[currentValue[criteria]] = [];
}
acc[currentValue[criteria]].push(currentValue);
return acc;
}, {});
return newObj;
}
Test it here: