Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Javascript - Remove array elements if all elements are null

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: ""}

Answer*

Draft saved
Draft discarded
Cancel
3
  • You beat me to it again 😁! Always nice to see your answers! 👍 Commented Jan 30, 2022 at 10:06
  • Thank you so much, it works. Really like the one line solution Commented Jan 30, 2022 at 10:07
  • @CarstenMassmann Agreed. Her answers are amazing! She is a developer from GOD. Commented Jan 31, 2022 at 11:05

lang-js

AltStyle によって変換されたページ (->オリジナル) /