检查嵌套对象中是否存在键值对

时间:2015-08-07 05:59:14

标签: javascript

假设我有一个对象,

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

我有一个数组

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

我想循环数组并检查myObj是否包含数组中的字段。

如何实现这一目标? 我只是不能测试:

if myObj['person.name']
    console.log('hr')

4 个答案:

答案 0 :(得分:4)

您可以在嵌套对象中无需循环检查键和值

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

答案 1 :(得分:1)

您在使用功能查看属性访问字符串之后,我确信这可以更加简洁,但它现在避开了我:

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

答案 2 :(得分:0)

使用此条件

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

您可以在这里查看

typeof myObj.person.name

答案 3 :(得分:0)

你可以这样思考(编辑n°4后测试,它有效!)

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);
相关问题