I have the following JS array. What's the best way to remove all rows with undefined keys?
json=[{email: "[email protected]", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
{email: "", first: undefined, last: undefined, gender: undefined, phone: undefined},
(...)];
I've tried the following code but is not working. What am I doing wrong?
cleanEmptyRows(json){
var i=0;
var row_to_remove=[];
json.forEach(function(element) {
for (var key in element) {
if(element[key]==null){
row_to_remove.push(i);
break;
}
}
i++;
});
row_to_remove.forEach(function(element){
var index = json.indexOf(element);
if (index > -1) {
json.splice(index, 1);
}
});
Simple solution JSON.parse(JSON.stringify(x)),
var t = [{email: "[email protected]", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
{email: "", first: undefined, last: undefined, gender: undefined, phone: undefined}];
console.log(JSON.parse(JSON.stringify(t)));
If you want to remove the entire row, you can follow the below code,
var t = [{email: "[email protected]", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
{email: "", first: undefined, last: undefined, gender: undefined, phone: undefined},
{email: "[email protected]", first: "Joao", last: "Bastos", gender: "Male", phone: undefined}];
var resultArray = t.filter((row) => {
var ignoreValue = Object.values(row).some(elem => elem === undefined);
return !ignoreValue ? true : false;
});
console.log(resultArray);