有三个这样的对象数组:
sections = [{ _id: '123'}]
groups = [{ _id: '456', parent: '123' }]
items = [{ _id: '789', parent: '456' }]
这是一个有效的数据集。当然,数组中有多个对象。
现在我想检查每个部分是否至少有一个子组,每个组至少有一个项目。
如果此检查失败,则应返回false
值。
示例
sections = [{ _id: '123'}]
groups = [{ _id: '456', parent: '123' }]
items = [{ _id: '789', parent: 'something' }]
complete = false
在此示例中,应返回false,因为该组没有子项。
我尝试从forEach循环开始,但这是一次错误的尝试:
let complete = true
sections.forEach(s => {
if (groups.filter(g => { return g.parent === s._id }).length === 0)
complete = false
})
答案 0 :(得分:3)
看起来你有三个数组。两个包含用作父元素的对象,两个包含用作子元素的对象。您想检查父项列表中的每个父项是否都有已定义的子项。
可以使用辅助函数everyParentHasChild(parents, children)
来实现此功能,该函数基于更高级别的数组方法Array#every
和Array#some
。
let sections = [{ _id: '123'}]
let groups = [{ _id: '456', parent: '123' }]
let items = [{ _id: '789', parent: '456' }]
let everyParentHasChild = (parents, children) => parents.every(
parent => children.some(child => child.parent === parent._id)
)
let result = everyParentHasChild(sections, groups) && everyParentHasChild(groups, items)
console.log(result) //=> true
答案 1 :(得分:0)
const sections = [{ _id: '123'}];
const groups = [{ _id: '456', parent: '123' }];
const items = [{ _id: '789', parent: 'something' }];
const isComplete = function() {
// check sections
for (const section of sections) {
if (!groups.filter(group => group.parent == section._id).length) {
return false;
}
}
// check groups
for (const group of groups) {
if (!items.filter(item => item.parent == group._id).length) {
return false;
}
}
return true;
};
console.log(isComplete());