3

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 !

2
  • 1
    See if the following helps any: quora.com/… Commented Jun 28, 2016 at 14:21
  • 1
    "I don't know how to recursive" - have you tried learning it, e.g. here? If you don't know how to start, try writing the function without (thinking about) recursive calls, for one level nested objects, then two levels deep, then three… Once you can see the pattern, you will know where to put the recursive call. Commented Jun 28, 2016 at 14:38

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

Since the OP explained he doesn't fully understand recursion, just giving the code doesn't really help. You should explain what it does.
also, this function doesn't return anything, which isn't the usage OP requested.
also, this function doesn't work with arrays
You are right I updated the answer as per comments. Thank you very much
0

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

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.