Cosider the following array:
let array = [
{Product Title: "Milk", Product Variant: "2L", Quantity: "3"},
{Product Title: "Water", Product Variant: "", Quantity: "3"},
{Product Title: "Pepsi", Product Variant: "", Quantity: ""},
{Product Title: "", Product Variant: "", Quantity: ""}
{Product Title: "", Product Variant: "", Quantity: ""}
]
How do I remove elements from the array, if all the elements have no value?
What I've tried:
let contents = []
for (let i in array) {
Object.keys(array[i]).forEach((k) => array[i][k] == "" && delete array[i][k])
contents.push(array[i])
}
console.log(contents)
but this returns:
0: {Product Title: "Milk", Product Variant: "2L", Quantity: "3"},
1: {Product Title: "Water", Quantity: "3"},
2: {Product Title: "Pepsi"},
3: {}
4: {}
While I would want:
0: {Product Title: "Milk", Product Variant: "2L", Quantity: "3"},
1: {Product Title: "Water", Product Variant: "", Quantity: "3"},
2: {Product Title: "Pepsi", Product Variant: "", Quantity: ""}
You could join all values and take the string for filtering.
const
array = [{ ProductTitle: "Milk", ProductVariant: "2L", Quantity: "3" }, { ProductTitle: "Water", ProductVariant: "", Quantity: "3" }, { ProductTitle: "Pepsi", ProductVariant: "", Quantity: "" }, { ProductTitle: "", ProductVariant: "", Quantity: "" }, { ProductTitle: "", ProductVariant: "", Quantity: "" }],
result = array.filter(o => Object.values(o).join(''));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This should do it:
const array = [
{"Product Title": "Milk", "Product Variant": "2L", Quantity: "3"},
{"Product Title": "Water", "Product Variant": "", Quantity: "3"},
{"Product Title": "Pepsi", "Product Variant": "", Quantity: ""},
{"Product Title": "", "Product Variant": "", Quantity: ""},
{"Product Title": "", "Product Variant": "", Quantity: ""}
]
const res=array.filter(e=>Object.values(e).join("")>"")
console.log(res)
try this:
let newArray = contents.filter(value => Object.keys(value).length !== 0);
Use filter on your array to have a new one without empty objects