<分区>
如何检查深层嵌套对象是否包含值? 我想检查给定对象是否包含例如包含“where”的属性值:
let data = {
name: 'Somebody',
address: {
city: 'somewhere'
},
tags: [{
id: 5
name: 'new'
}]
}
check(data, 'where') // should be true
标签 javascript object
<分区>
如何检查深层嵌套对象是否包含值? 我想检查给定对象是否包含例如包含“where”的属性值:
let data = {
name: 'Somebody',
address: {
city: 'somewhere'
},
tags: [{
id: 5
name: 'new'
}]
}
check(data, 'where') // should be true
最佳答案
您可以使用如下所示的递归函数
,它会遍历键并检查类型。如果类型是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
关于javascript - 检查文本是否存在于深层嵌套对象的值中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244258/