0

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?

3
  • So you want to set the property to empty array if it is an array and null otherwise? Commented May 1, 2017 at 2:50
  • @Saravana yes that's it Commented May 1, 2017 at 2:51
  • What I don't understand is how did you think that your solution should set it to a blank array. "Am I missing something?" :D please try to use google first Commented May 1, 2017 at 23:04

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Thank you for this.

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.