检查深层嵌套对象中的值是否存在文本?

时间:2016-12-20 14:08:20

标签: javascript object

如何检查包含值的深层嵌套对象? 我想检查给定对象是否包含例如包含“where”的属性值:

axios.get('./static/PanelReportDataFilled.json')
      .then((response) => {
      var submitted=this.state.submitted==0?1:0;
      console.log('inside http method',submitted);
      this.setState({
        allocatedBudgetData:response.data,
        submitted:submitted
      });

    })

1 个答案:

答案 0 :(得分:4)

您可以使用下面的recursive function,它会迭代键并检查类型。如果类型为objectarray,则会调用递归检查。

工作代码

let data = {
    name: 'Somebody',
    address: {
        city: 'somewhere'
    },
    tags: [{
        id: 5,
        name: 'new'
    }]
};

const check = (obj, text) => {
  var exists = false;
  var keys = Object.keys(obj);
  for(var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var type = typeof obj[key];
    if(type === 'object') {
      exists = check(obj[key], text);
    } else if(type === 'array') {
      
      for(var j = 0; j < obj[key].length; j++) {
        exists = check(obj[key][j], text);
    
        if(exists) {
          break;
        }
      }
      
    } else if(type === 'string') {
      exists = obj[key].indexOf(text) > -1;
    }
    
    if(exists) {
      break;
    }
  }
       
  return exists;
};

console.log(check(data, 'where')); // should be true