I need to replace nested arrays inside a main array that have null values like lets say [null, null]
or the nested arrays that are empty with a string value like "empty"
.
Saying that we have the following array:
array = [
{
id: 123,
name: 'Peter',
phone: [null, null],
addresses: [{ address1: 'Manchester, UK', address2: 'London, UK' }]
},
{
id: 124,
name: 'Sara',
phone: [],
addresses: [{ address1: 'London, UK', address2: 'Paris, FR' }]
}
];
We see that, the first array has phone: [null, null]
and the second has it as []
. What I need to do it to transform them into the following:
array = [
{
id: 123,
name: 'Peter',
phone: "empty",
addresses: [{ address1: 'Manchester, UK', address2: 'London, UK' }]
},
{
id: 124,
name: 'Sara',
phone: "empty",
addresses: [{ address1: 'London, UK', address2: 'Paris, FR' }]
}
];
This is an example, and each array might contain multiple nested arrays that have the same [null, null]
or []
.
I tried the following:
var filtered = this.array.map(subarray => subarray.filter(el => el != null));
from this Stack Overflow answer, but I've got an error saying:
Error: subarray.filter is not a function
Then I tried a second method using lodash's
every()
and isNull
method and property but couldn't figure it out:
let props = [];
props = Array.from(new Set(this.array.flatMap(e => Object.keys(e), [])));
console.log(props)
for (const prop of props) {
this.array.forEach(e => {
if ((Array.isArray(e[prop]) || typeof(e[prop]) === 'object') && e[prop]._.every(_.isNull)) {
console.log(e)
}
});
}
I searched few questions on Stack Overflow but the structure of the arrays are like: [ [1, 2], [1,3]...]
and not like my array's structure [{...}, {...}]
, so I tried some of the solution and got the same error of method 1 above.
Here is a stackblitz.