简体   繁体   English

如何在JavaScript中将对象属性设置为null和空白数组?

[英]How to set object properties to null and blank array in JavaScript?

So I have this object for example: 所以我有这个对象例如:

family_background: {
      children: [],
      spouse_surname: null,
      spouse_first_name: null,
      spouse_first_name: null,
      spouse_middle_name: null,
      spouse_occupation: null,
      spouse_employer: null,
      // so forth and so on
}

The way I set the values to null is like this: 我将值设置为null的方式是这样的:

  for (var key in family_background) {
    family_background[key] = null;
  }

But I have a property that is equal to an array and by doing the loop, it would set the property to null also instead of a blank array. 但是我有一个等于数组的属性,通过执行循环,它会将属性也设置为null,而不是空白数组。

How can I fix this? 我怎样才能解决这个问题? Am I missing something? 我想念什么吗?

Use Array.isArray to check if your property is an array before you set the values: 在设置值之前,请使用Array.isArray检查您的属性是否为数组:

for (var key in family_background) {
    family_background[key] = Array.isArray(family_background[key]) ? [] : null;
}

MDN documentation for Array.isArray : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray Array.isArray MDN文档: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

Check if the value is an instanceof Array , and if so, set it to an empty array. 检查该值是否为instanceof Arrayinstanceof Array ,如果是,则将其设置为空数组。

for (var key in family_background) {
    family_background[key] = family_background[key] instanceof Array
        ? []
        : null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM