-2

I am trying to check for an empty value in a nested object, how would I loop through the nested properties?

for (var propt in updatedInputs) {

  if (updatedInputs[propt] == "") this.cancelSubmit();

  // check for nested properties
  if (updatedInputs.hasOwnProperty(propt)) {

    // loop through nested properties here

  }
}

Sample object:

Object {contacts: Array[5]}
    contacts: Array[5]
    0: "04354355"
    1: "24349878779"
    2: "wqewqewqeqw"
    3: "wqewqeqwe"
    4: ""
Bomber
  • 10,195
  • 24
  • 90
  • 167
  • 3
    Please give sample object – RIYAJ KHAN Feb 03 '16 at 18:59
  • You mean if one of the nested properties were an array or an object? – Travis J Feb 03 '16 at 18:59
  • That sample object isn't a valid js object, the syntax is wrong. Also, are you trying to loop through a nested array or a nested object? – nem035 Feb 03 '16 at 19:05
  • Can you please show how `updatedInputs` looks like? Or be more specific on which type (array or object) you are looping on, and, if needed, how many nested levels you need to check. – nem035 Feb 03 '16 at 19:18
  • 1
    This is completely unclear what you are working with. Your broken code showing undefined variables is not a good substitute for a proper explanation and reasonable sample of input data and expected results – charlietfl Feb 03 '16 at 19:21

1 Answers1

2

Fine I think it'll do what you want now.

function iterObj(obj) {

  for (var key in obj) {
    console.log(key + ': ' + obj[key]);
    if (obj[key] !== null && typeof obj[key] === "object") {
      // Recurse into children
      iterObj(obj[key]);
    }
  }
}
wrleskovec
  • 326
  • 1
  • 7
  • This will only work if `updateInputs` is an array but the OP says he's looping over an object. There's no such thing as `forEach` on an object. – nem035 Feb 03 '16 at 19:13
  • If it did, then there would be no point for `$.each()` ^_^ – nem035 Feb 03 '16 at 19:15