1

I have the following JS array. What's the best way to remove all rows with undefined keys?

json=[{email: "1234569@hhh.pt", 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);
    }
});
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345

3 Answers3

5

Simple solution JSON.parse(JSON.stringify(x)),

var t = [{email: "1234569@hhh.pt", 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: "1234569@hhh.pt", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
      {email: "", first: undefined, last: undefined, gender: undefined, phone: undefined},
      {email: "1234569@hhh.pt", 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);
Prince Devadoss
  • 416
  • 3
  • 6
0

One simple way is to stringify and parse the JSON.

let jsonTest = { foo: 'foo', bar: undefined };
let allDefined = JSON.parse(JSON.stringify(jsonTest));

You could also do it by deleting undefined properties. You could make it recursive if you don't have a flat object.

let jsonTest = { foo: 'foo', bar: undefined };
Object.keys(jsonTest).forEach((key) => {

    if (typeof jsonTest[key] == 'undefined') { 

        delete jsonTest[key];
    }
});
JerMe
  • 1
  • 1
0

Try

json.map(x=> Object.keys(x).map(k=> x[k]===undefined ? delete x[k]:0)); 

let json=[{email: "1234569@hhh.pt", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
      {email: "", first: undefined, last: undefined, gender: undefined, phone: undefined}, 
      ];
      
json.map(x=> Object.keys(x).map(k=> x[k]===undefined ? delete x[k]:0)); 

console.log(json);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345