Considere la siguiente matriz:
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: ""} ]
¿Cómo elimino elementos de la matriz, si todos los elementos no tienen valor?
Lo que he probado:
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)
pero esto devuelve:
0: {Product Title: "Milk", Product Variant: "2L", Quantity: "3"}, 1: {Product Title: "Water", Quantity: "3"}, 2: {Product Title: "Pepsi"}, 3: {} 4: {}
Mientras que yo querría:
0: {Product Title: "Milk", Product Variant: "2L", Quantity: "3"}, 1: {Product Title: "Water", Product Variant: "", Quantity: "3"}, 2: {Product Title: "Pepsi", Product Variant: "", Quantity: ""}
Puede unir todos los valores y tomar la cadena para filtrar.
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; }
Esto debería hacerlo:
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)
prueba esto:
let newArray = contents.filter(value => Object.keys(value).length !== 0);
Use el filtro en su matriz para tener una nueva sin objetos vacíos