我想使用 javascript 检查子对象是否存在于对象数组中。数据结构如下所示,
假设我将数据存储在变量 arr_obj 中,那么我尝试使用
if (arr_obj && arr_obj[0].children && arr_obj[0].children.length > 0) {
console.log("children exists")
}
if (arr_obj && !arr_obj[0].children) {
console.log("children doesnt exist")
}
当 Children 数组为 0 时,条件 (arr_obj && !arr_obj[0].children) 会抛出错误“无法读取未定义的属性子项”有人可以帮我解决这个问题。谢谢。
最佳答案
*编辑您还应该首先检查数组 (arr_obj && arr_obj.length > 0 && arr_obj[0].hasOwnProperty('children') && arr_obj[0].children.length > 0 ) 则为真,否则为假。
如果我正确理解你的问题。我只是按照您上面描述的方式制作该对象。我认为使用过滤器、 map 或归约内的过滤器,您可以完成您的工作。您应该明白为什么要使用 MDN 中的内容。 。这将返回一个 bool 值。如果 true 元素存在,如果 false 则不存在。第一个控制台检查它是否有特定的子级,第二个控制台检查它是否有如上所述的子级。
var obj = [];
var parent1 = {};
parent1.children = [];
parent1.children.push({
name: 'parent1_somename1'
})
parent1.children.push({
name: 'parent1_somename2'
});
obj.push(parent1);
var parent2 = {};
parent2.children = [];
parent2.children.push({
name: 'parent2_somename1'
})
parent2.children.push({
name: 'parent2_somename2'
})
obj.push(parent2);
function checkIfExists(arrList, searchedItem) {
var results = arrList.filter(function(element) {
var resultsChild = element.children.filter(function(childElement) {
return childElement.name === searchedItem;
});
if (resultsChild.length > 0) {
return true;
} else {
return false;
}
})
return results;
}
function checkIfItHasChildren(arrList) {
var results = arrList.map(function(element) {
return element.children.length > 0;
if (results.length > 0) {
return true;
} else {
return false;
}
})
return results;
}
// Check if specific children exists
if (obj && checkIfExists(obj, 'parent2_somename2').length > 0) {
console.log("children exists")
} else {
console.log("children doesnt exist")
}
// Check if array has childrens
if (obj && checkIfItHasChildren(obj).length > 0) {
console.log("It has children")
} else {
console.log("It doesnt has children")
}
关于javascript - 如何使用 javascript 检查子对象是否存在于对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394091/