Jax Teller
Jax Teller

Reputation: 1467

Javascript null to empty object properties

For some reasons, i need a function to convert an object inside an array with null property to an object with empty object property.

The function should be recursive, and must work for any object (deep nested, array in array, array in object, etc...)

There is an example of what i need :

var obj = {
    "parent" : [
    null,
    {"child" : 2},
    {"child" : 3}
  ],
  "parent2" : {
    "parent3" : [
      {"child" : 1},
      null,
      {"child" : 3}
    ]
  },
  "parent4" : [
     {"child" : [
         {"childa" : 1},
         {"childa" : 2},
         null
       ]
     },
     {"child" : [
         {"childa" : 1},
         null,
         null
       ]
     }, 
     null
  ]
}

Then :

var obj2 = nullToEmptyObject(obj);

And obj2 should look like this :

{
  "parent" : [
    {},
    {"child" : 2},
    {"child" : 3}
  ],
  "parent2" : {
    "parent3" : [
      {"child" : 1},
      {},
      {"child" : 3}
    ]
  },
  "parent4" : [
     {"child" : [
         {"childa" : 1},
         {"childa" : 2},
         {}
       ]
     },
     {"child" : [
         {"childa" : 1},
         {},
         {}
       ]
     }, 
     {}
  ]
}

I didn't do anytry yet, because i don't know how to recursive. If you can give me a starting code, i could complete.

Thanks guy, edit me if my english is bad !

Upvotes: 3

Views: 2287

Answers (3)

Jack jdeoel
Jack jdeoel

Reputation: 4584

Just recall current function again , coz all inside multi data are also objects and even you need to check is null only..

function nullToEmptyObject(o){
  for(var i in o){
    if(o[i] == null){
      o[i] = {};
    }
    else{
    nullToEmptyObject(o[i]);
    }
  }
}
nullToEmptyObject(obj);
console.log(JSON.stringify(obj,0,4));

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122155

You can use recursion first to check if element is object and use for-in loop and check if each element is null or keep looping and then check for array with forEach and repeat same test. Any time function finds null it will be changed to {}

var obj = {"parent":[null,{"child":2},{"child":3}],"parent2":{"parent3":[{"child":1},null,{"child":3}]},"parent4":[{"child":[{"childa":1},{"childa":2},null]},{"child":[{"childa":1},null,null]},null]}

function nullToEmptyObject(el) {
  //Check for object not array and loop with for-in. If the returned value is null change to object else keep looping with recursion 
  if (typeof el === 'object' && !Array.isArray(el)) {
    for (var p in el) {
      (el[p] !== null) ? nullToEmptyObject(el[p]): el[p] = {}
    }
    //Check for Array and loop with forEach. If the returned value is null change to object else keep looping with recursion .
  } else if (Array.isArray(el)) {
    el.forEach(function(e, i) {
      (e !== null) ? nullToEmptyObject(e): el[i] = {}
    })
  }
}

nullToEmptyObject(obj);
console.log(JSON.stringify(obj, 0, 4))

As test here is more complicated example of data with more nested elements inside first parent property in object

var obj = {
  "parent": [
    null, [null, {
      'random': null,
      'moreRandom': {
        'moreRandom': {
          'moreRandom': null,
          'random': [null, null]
        }
      }
    }], {
      "child": 2
    }, {
      "child": 3
    }
  ],
  "parent2": {
    "parent3": [{
        "child": 1
      },
      null, {
        "child": 3
      }
    ]
  },
  "parent4": [{
      "child": [{
          "childa": 1
        }, {
          "childa": 2
        },
        null
      ]
    }, {
      "child": [{
          "childa": 1
        },
        null,
        null
      ]
    },
    null
  ]
}

function nullToEmptyObject(el) {
  //Check for object not array and loop with for-in. If the returned value is null change to object else keep looping with recursion 
  if (typeof el === 'object' && !Array.isArray(el)) {
    for (var p in el) {
      (el[p] !== null) ? nullToEmptyObject(el[p]): el[p] = {}
    }
    //Check for Array and loop with forEach. If the returned value is null change to object else keep looping with recursion .
  } else if (Array.isArray(el)) {
    el.forEach(function(e, i) {
      (e !== null) ? nullToEmptyObject(e): el[i] = {}
    })
  }
}

nullToEmptyObject(obj);
console.log(JSON.stringify(obj, 0, 4))

Upvotes: 1

pinturic
pinturic

Reputation: 2263

You can try with something like this:

function nullToEmptyObject(obj){
    var obj2 = {}:
    for (var k in obj)
    {
        if (obj[k] === null)
            obj2[k] = {};
        else if (typeof obj[k] == "object")
            obj2[k] = nullToEmptyObject(obj[k]);
        else if (Array.isArray(obj[k])){
           obj2[k] = []
           for (i=0; i<obj[k].length; i++) {
               obj2.push(nullToEmptyObject(obj[k][i]);
           }
        }
    }
    return obj2; 
}

The function is cycling over all the object properties and changing them as desired:

  1. When the property is null it is set to {}
  2. When the property is object it descends in the tree
  3. When the property is an array it is looping over it

Upvotes: 1

Related Questions