1๐
โ
There are many ways to do this.
If you actually want to delete
the properties, here is one way:
let array = [
{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
]
array.forEach(obj => {
delete obj.variantName;
delete obj.price;
delete obj.productName;
});
console.log(array);
2๐
You can use Array.prototype.map
[
{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
].map(({id, variant, extrasSelected, qty}) => ({id, variant, extrasSelected, qty}))
2๐
Just do a destructuring inside a .map
const data = [
{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
];
// 1
const result = data.map(({ id, variant, extrasSelected, qty }) => ({
id,
variant,
extrasSelected,
qty
}));
// Detailed explanation
// 2
// 2 is same as 1
const result2 = data.map((item => {
const { id, variant, extrasSelected, qty } = item;
return { id, variant, extrasSelected, qty };
}));
// 3
// 3 is same as 2
const result3 = data.map((item) => {
const id = item.id;
const variant = item.variant;
const extrasSelected = item.extrasSelected;
const qty = item.qty;
return {
id: id,
variant: variant,
extrasSelected: extrasSelected,
qty: qty
}
});
console.log(result);
/*
[
{ id: 111, variant: 9, extrasSelected: [], qty: '1' },
{ id: 112, variant: 25, extrasSelected: [], qty: '1' }
]
*/
2๐
Variation on the above solutions. Use Array.Map
and rest parameters.
const data = [{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
]
const result = data.map(({
productName,
variantName,
...rest
}) => rest);
console.log(JSON.stringify(result, null, 4));
Source:stackexchange.com