Javascript null为空对象属性

Javascript null to empty object properties

本文关键字:对象 属性 null Javascript      更新时间:2023-09-26

由于某些原因,我需要一个函数将数组中的对象转换为具有空对象属性的对象。

函数应该是递归的,并且必须适用于任何对象(深度嵌套,数组中的数组,数组中的对象,等等…)

有一个我需要的例子:

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
  ]
}

var obj2 = nullToEmptyObject(obj);

obj2应该是这样的:

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

我还没有做任何尝试,因为我不知道如何递归。如果你能给我一个起始代码,我可以完成。

谢谢你,如果我的英语不好,请编辑我!

您可以首先使用递归来检查元素是否为对象,并使用for-in循环并检查每个元素是否为null或继续循环,然后使用forEach检查数组并重复相同的测试。任何时间函数发现null,它将更改为{}

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

作为测试,这里是一个更复杂的数据示例,在对象

的第一个parent属性中嵌套了更多元素。

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

你可以尝试这样做:

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

函数循环遍历所有对象属性并根据需要更改它们:

  1. 当属性为null时,它被设置为{}
  2. 当属性是object时,它在树中向下。
  3. 当属性为数组时,它将在其上循环

请再次调用当前函数,因为multidata中的所有内容都是对象,甚至您只需要检查是否为null .

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