Im using Angular8, want to remove empty object from an array, and get its length
Array: [
{data01: "abc", data02: "cde", data03: "fgh", data04: "", data05: ""},
{data01: "abc", data02: "cde", data03: "", data04: "", data05: ""},
{data01: "abc", data02: "cde", data03: "fgh", data04: "ijk", data05: "lmn"},
{data01: "abc", data02: "", data03: "", data04: "", data05: ""},
]
then I want it be like
Array: [
{data01: "abc", data02: "cde", data03: "fgh"},
{data01: "abc", data02: "cde"},
{data01: "abc", data02: "cde", data03: "fgh", data04: "ijk", data05: "lmn"},
{data01: "abc"},
]
is that anyway to do it ?
I tried to push those element in a new array like
_Array: ["abc","cde", "fgh", "", "", ....]
and chunk it by 5 then filter(Boolean), it works, but the performance was bit slow, any other way to improve the performance?
You can use the map() and filter() of Array object methods in JS to solve the problem.
let array = [
{data01: "abc", data02: "cde", data03: "fgh", data04: "", data05: ""},
{data01: "abc", data02: "cde", data03: "", data04: "", data05: ""},
{data01: "abc", data02: "cde", data03: "fgh", data04: "ijk", data05: "lmn"},
{data01: "abc", data02: "", data03: "", data04: "", data05: ""},
]; // array provided
array = array.map(object => {
let entries = Object.entries(object); //for each element in the array get the entries, [key, value] pair
entries = entries.filter(([key, value]) => value !== ""); // remove the elements which has "" values
return Object.fromEntries(entries);
});
console.log(array.length);
// shorter version
array = array.map(object => Object.fromEntries(Object.entries(object).filter(([key, value]) => value !== "")));
console.log(array.length);
There is a possibility the resultant array might contain an empty object if the input array had a object which had all the entries ""(empty string). Eg: {data01: "", data02: "", data03: "", data04: "", data05: ""}. In this case we need another filter() to remove the empty object from the resultant array.
let array = [
{data01: "abc", data02: "cde", data03: "fgh", data04: "", data05: ""},
{data01: "abc", data02: "cde", data03: "", data04: "", data05: ""},
{data01: "abc", data02: "cde", data03: "fgh", data04: "ijk", data05: "lmn"},
{data01: "abc", data02: "", data03: "", data04: "", data05: ""},
]; // array provided
array = array.map(object => {
let entries = Object.entries(object);
entries = entries.filter(([key, value]) => value !== "");
return Object.fromEntries(entries);
});
// remove the empty object if present
array = array.filter(object => Object.entries(object).length !== 0);
console.log(array.length);
// shorter version
array = array.map(object => Object.fromEntries(Object.entries(object).filter(([key, value]) => value !== ""))).filter(object => Object.entries(object).length !== 0);
// the filter() at the end removes the empty object
console.log(array.length);
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