0

The json format is like that:

 [
  [
  {},
  {
  "Country": "Japan",
  "cityName": "tokyo",
  "onto": [
    {
      "level1": "one",
      "articles": [
        null,
        {
          "id": "114506604",
          "name": "bunya3",           
          "abc": [
             {
              "filename": "attachmentsfilename3",
              "size": 3
             }
           ],
          "image": {}
        }
      ]
    }
  ]
 }
 ],
 [
 {}
 ]
]

We can see few null, {} and [{}]. How can we remove it ? By the way I am using node js. I have tried by nnjson

nnjson.removeNull(obj_summary);

But not works object without key.

Suman Kumar Dash
  • 681
  • 5
  • 19
  • Please check if this helps - https://stackoverflow.com/questions/38275753/how-to-remove-empty-values-from-object-using-lodash – Raj Mar 10 '20 at 04:38
  • Traverse the json recursively (post-order traversal because you want to delete [{}] as well) and delete any unwanted object/array at the end of post order traversal of that object/array. – Tuhin Paul Mar 11 '20 at 00:14
  • Does this answer your question? [How to remove empty values from object using lodash](https://stackoverflow.com/questions/38275753/how-to-remove-empty-values-from-object-using-lodash) – Rahul Soni Feb 02 '22 at 12:02

2 Answers2

0

If we assume that your data is always going to be an array, we can map over it and remove empty arrays and objects from the first level:

const data = [
  [
    {},
    {
      Country: 'Japan',
      cityName: 'tokyo',
      onto: [
        {
          level1: 'one',
          articles: [
            null,
            {
              id: '114506604',
              name: 'bunya3',
              abc: [
                {
                  filename: 'attachmentsfilename3',
                  size: 3
                }
              ],
              image: {}
            }
          ]
        }
      ]
    }
  ],
  [{}]
]

function clean(input) {
  return input
    .map(item => {

      // remove empty arrays
      if (Array.isArray(item) && item.length === 0) {
        return null
      }

      // Remove empty objects
      if (item instanceof Object && Object.keys(item).length === 0) {
        return null
      }

      return item
    })
    .filter(item => item)
}

console.log(clean(data))
Tom
  • 2,543
  • 3
  • 21
  • 42
0

I found the solution.

  1. To remove null I used:

    let retSummary = JSON.parse(stringifySummary, (k, v) => Array.isArray(v) ? 
    v.filter(e => e !== null) : v);
    
  2. To remove {} I used

    var newArray = parObj.filter(value => Object.keys(value).length !== 0);
    
Dharman
  • 30,962
  • 25
  • 85
  • 135
Suman Kumar Dash
  • 681
  • 5
  • 19