-2

I would like to check if an object has a child object array

for example

{
   "parent_category_id": "ABC",
   "parent_category_name": "ABC COMPANY",
   "place_id": 733,
   "industry": {
       "@nil": "true"
   }
   "street_id": 733
}

How would you check if the "Industry" object would have a child array. Like if "Industry" has a child array value of "@nil: true". Then alert Has Child

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Jon
  • 384
  • 6
  • 18
  • 3
    i see no array. – Nina Scholz Dec 06 '17 at 08:28
  • your `object.industry` is a plain js object not an array. It is not clear what you are looking for?! – A. Wolff Dec 06 '17 at 08:30
  • 1
    @Martijn: That's for the OP to fix. The misunderstanding of what's what may be the crux of the problem. – Cerbrus Dec 06 '17 at 08:32
  • Please clarify your quesion, what array are you expecting? And `@nil: true` is not an array value, it's an attribute of an object of type boolean or string in your code snippet. – M0nst3R Dec 06 '17 at 08:38
  • @GhassenLouhaichi: same comment as I made to Martijn: Don't change the wording of the question. The misunderstanding there may well be the reason for the question. – Cerbrus Dec 06 '17 at 08:58

4 Answers4

1

You can check with the instanceof operator.

For example:

var t = {
    "parent_category_id": "ABC",
    "parent_category_name": "ABC COMPANY",
    "place_id": 733,
    "industry": {
        "@nil": "true"
    },
    "street_id": 733
};

After it, you can use:

t.industry instanceof Object // result is: true
t.industry instanceof Array  // result is: false
M0nst3R
  • 5,186
  • 1
  • 23
  • 36
FarukT
  • 1,560
  • 11
  • 25
0

If you simply want to check if an object has children and is not empty you can either do an IF statement like:

if (obj.industry) {}

or like this using the Object.getOwnPropertyNames(obj) method which will return the names of all properties within an object:

var obj = {
   "parent_category_id": "ABC",
   "parent_category_name": "ABC COMPANY",
   "place_id": 733,
   "industry": {
       "@nil": "true"
   },
   "street_id": 733
};
var names = Object.getOwnPropertyNames(obj.industry);

names.forEach(name => console.log('Property/Value ->', name, obj.industry[name]));
anteAdamovic
  • 1,462
  • 12
  • 23
0

You can do:

info = {
  "string": "ABC",
  "array": [1, 2, 3],
  "object": {
    "key": "value"
  },
  "object(empty)": {},
}

function isEmpty(obj) {
  if (obj instanceof Object && !(obj instanceof Array)) {
    for (var i in obj) {
      if (hasOwnProperty.call(obj, i)) return false;
    }
  }
  return true;
}

for (var i in info) {
  if (isEmpty(info[i]) == false) {
    console.log(info[i]);
  }
}

Reference: Is object empty?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
-1
Array.isArray(parentobj.industry)

if you meant to check if it is an array or not

Loredra L
  • 1,485
  • 2
  • 16
  • 32