如何检查包含值的深层嵌套对象? 我想检查给定对象是否包含例如包含“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
});
})
答案 0 :(得分:4)
您可以使用下面的recursive function
,它会迭代键并检查类型。如果类型为object
或array
,则会调用递归检查。
工作代码:
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