wobsoriano
wobsoriano

Reputation: 13442

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:

  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.

How can I fix this? Am I missing something?

Upvotes: 0

Views: 5001

Answers (2)

Saravana
Saravana

Reputation: 40604

Use Array.isArray to check if your property is an array before you set the values:

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

Upvotes: 2

Mikal Madsen
Mikal Madsen

Reputation: 579

Check if the value is an instanceof Array, and if so, set it to an empty array.

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

Upvotes: 2

Related Questions