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.

3
  • Please check if this helps - stackoverflow.com/questions/38275753/… Commented Mar 10, 2020 at 4: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. Commented Mar 11, 2020 at 0:14
  • Does this answer your question? How to remove empty values from object using lodash Commented Feb 2, 2022 at 12:02

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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);
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.