I have an array of objects like this below.
[
{
product_id: 4,
product_name: "Samsung",
category_name: "Tv and home appliance",
is_Available: 1
},
{
product_id: 8,
product_name: "Apple",
category_name: "Home gadgets",
is_Available: 1
},
{
product_id: 9,
product_name: "Verifone",
category_name: "Electronics",
is_Available: 0
}
]
I want to split this array into two based on is_Available flag value. So i did like this using reduce.
const formmattedResponse = data.reduce((arr,el) => {
if(el.is_Available === 1) {
arr.push({...el});
}
return arr;
},[]);
But, i need this type of formatted data like below based on above data array
{
availableData: [{
product_id: 4,
product_name: "Samsung",
category_name: "Tv and home appliance",
is_Available: 1
},
{
product_id: 8,
product_name: "Apple",
category_name: "Home gadgets",
is_Available: 1
}
],
notAvailableData: [{
product_id: 9,
product_name: "Verifone",
category_name: "Electronics",
is_Available: 0
}
]
}
UPDATE 2024
With Object.groupBy, it goes shorter by taking a group value.
const
data = [{ product_id: 4, product_name: "Samsung", category_name: "Tv and home appliance", is_Available: 1 }, { product_id: 8, product_name: "Apple", category_name: "Home gadgets", is_Available: 1 }, { product_id: 9, product_name: "Verifone", category_name: "Electronics", is_Available: 0 }],
result = Object.groupBy(data, ({ is_Available }) => is_Available
? 'availableData'
: 'notAvailableData'
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could take an array and push the objects according their availability with a single loop.
const
data = [{ product_id: 4, product_name: "Samsung", category_name: "Tv and home appliance", is_Available: 1 }, { product_id: 8, product_name: "Apple", category_name: "Home gadgets", is_Available: 1 }, { product_id: 9, product_name: "Verifone", category_name: "Electronics", is_Available: 0 }],
result = data.reduce((r, o) => {
r[o.is_Available ? 'availableData' : 'notAvailableData'].push(o);
return r;
}, { availableData: [], notAvailableData: [] });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With