-3

How to remove objects properties which values are empty string for same key? For example, here I want to remove division key from object.

const data= [
  {
    "id": "1",
    "status": "Y",
    "role": "any",
    "division": "",
    "name" : "test"
  },
  {
    "id": "2",
    "status": "N",
    "role": "admin",
    "division": "",
    "name" : ""
  },
{
    "id": "3",
    "status": "N",
    "role": "test",
    "division": "",
    "name" : "any"
  }
]
Santraj Kumar
  • 215
  • 1
  • 2
  • 11
  • 1
    None of the objects have `null` values. If you mean empty string, then `name` key also should be removed from the second object. Or do you want to remove the keys which have empty / null value for ALL the objects in the array? Please create a [mcve] with a clear problem statement and the code you've tried – adiga Jun 26 '20 at 13:39
  • Yes, I mean empty string, and yes I want to remove only those keys which values are empty in all objects. Here I am referring division key. I don't want to remove name key, since name value is available in first and third object. – Santraj Kumar Jun 26 '20 at 13:45
  • 2
    Please update the question – adiga Jun 26 '20 at 13:51

1 Answers1

0

Something like this:

const data= [{
    "id": "1",
    "status": "Y",
    "role": "any",
    "division": "",
    "name" : ""
  }, {
    "id": "2",
    "status": "N",
    "role": "admin",
    "division": "",
    "name" : "any"
  }, {
    "id": "3",
    "status": "N",
    "role": "test",
    "division": "",
    "name" : "any"
  }];


  const mergedObject = data.reduce((akk, item) => {
    for (const [key, value] of Object.entries(item)) {
      if(typeof akk[key] === 'undefined') {
        akk[key] = '';
      }
      akk[key] += item[key];
    }
    return akk;
  }, {});
  
  data.map((arrayItem, index) => {
    for (const [key, value] of Object.entries(arrayItem)) {
      if(mergedObject[key].length === 0) {
        delete arrayItem[key]
      }
    }
    return arrayItem;
  });
  console.log(data);
Arthur Rubens
  • 4,626
  • 1
  • 8
  • 11