1

Suppose I have a object,

var myObj = {
    "person": {
        "name": 'adam',
        "age": 25
        "email": {
            "address": "this@that.com",
            "ccOnNot": true
        }
     }
}

And I have an array

['person.name', 'person.age', 'person.email.address']

I want to loop the array and check if myObj has the fields in array.

How can this be achieved? I simply cant test like:

if myObj['person.name']
    console.log('hr')
Suman Lama
  • 946
  • 1
  • 9
  • 26
  • This could help http://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript – bloC Aug 07 '15 at 06:04

4 Answers4

5

You can check key and value without loop in nested object

// check name and value
JSON.stringify(myObj).indexOf('"name":"adam"') == -1
2

You're after a function to go down a property access string, I'm sure this can be made more concise but it evades me for now:

function hasPropertyByString(obj, s) {
  return s.split('.').every(function(key){
     var result = obj.hasOwnProperty(key);
     if (obj) obj = obj[key];
     return  result;
  });
}

var obj = {one:'', two:undefined, three:{four:'three'}};

// Test empty string
console.log(hasPropertyByString(obj, 'one')); // true

// Test undefined value
console.log(hasPropertyByString(obj, 'two')); // true

// Test depth
console.log(hasPropertyByString(obj, 'three.four')); // true

// Test non-existent
console.log(hasPropertyByString(obj, 'three.five')); // false
RobG
  • 142,382
  • 31
  • 172
  • 209
0

use this condition

if(typeof myObj['person.name'] === "undefined")

Here you can check as like this

typeof myObj.person.name
benka
  • 4,732
  • 35
  • 47
  • 58
mathew
  • 193
  • 1
  • 5
  • The property might exist but have the value *undefined*, better to use *hasOwnProperty* or similar. – RobG Aug 07 '15 at 06:14
  • my question was not about checking if the property exists but to use string version of nested object to find if it exists. – Suman Lama Aug 07 '15 at 06:22
0

You can think something like this (after edit n°4 tested, it works!)

function hasPath(obj, path) {
    if (typeof obj == 'undefined')
        return false;
    var propName = path.shift();
    if ( obj.hasOwnProperty(propName) ) {
        if ( path.length == 0 )
            return true;
        else
            return hasPath(obj[propName], path);
    }
    return false;
}

var myObj = {
  "person": {
    "name": 'adam',
    "age": 25,
    "email": {
      "address": "this@that.com",
      "ccOnNot": true
    }
  }
}
var myArr = ['person.name', 'person.age', 'person.email.address'];

var hasAll = true;
for ( var i=0; i<myArr.length; i++ )
    if ( ! hasPath(myObj, myArr[i].split('.') ) )
        hasAll = false;

console.log(hasAll);
jperelli
  • 6,988
  • 5
  • 50
  • 85