Search code examples
javascriptjsonlodash

Javascript or lodash nested JSON object transformation


How to make nested object null

if object attributes has a null values. please check the JSON below

I have JSON data as following

[{
    "student": {
        "id": null,
        "name": null
    },
    "children": [{
        "student": null,
        "children": [{
                "student": {
                    "id": 1,
                    "name": "A"
                }
            },
            {
                "student": {
                    "id": null,
                    "name": null
                }
            }
        ]
    }]
}]


I want to convert it to following output

Expected

[{
    "student": null,
    "children": [{
        "student": null,
        "children": [{
                "student": {
                    "id": 1,
                    "name": "A"
                }
            },
            {
                "student": null
            }
        ]
    }]
}]

Solution

  • You could "nullify" values if their values are all null using the following conditional.

    Object.values(obj).every(value => value == null)
    

    I created a basic recursive function to below that traverses the object and checks to see if it needs to nullify an object. This is all done in-place, and it will modify the original object.

    const obj = [{
      "student": { "id": null, "name": null },
      "children": [{
        "student": null,
        "children": [
          { "student": { "id": 1, "name": "A" } },
          { "student": { "id": null, "name": null } }
        ]
      }]
    }];
    
    const nullify = (obj, key = null, parent = null) => {
      if (obj != null) {
        if (Array.isArray(obj)) {
          obj.forEach((item, index) => nullify(item, index, obj));
        } else if (typeof obj === 'object') {
          if (Object.values(obj).every(value => value == null)) {
            parent[key] = null;
          } else {
            Object.entries(obj).forEach(([key, value]) => nullify(value, key, obj));
          }
        }
      }
    };
    
    nullify(obj);
    
    console.log(obj);
    .as-console-wrapper { top: 0; max-height: 100% !important; }