Javascript 检查由标识符标识的子数组内主数组中的所有元素是否至少出现一次
我需要检查在由Javascript 检查由标识符标识的子数组内主数组中的所有元素是否至少出现一次,javascript,arrays,loops,object,foreach,Javascript,Arrays,Loops,Object,Foreach,我需要检查在由parent\u id标识的子列表中,mainList中的所有元素是否至少出现一次 我目前是如何做到这一点的 let mainList = [ 2, 3, 5]; let subList = [ { id: 23, name: "ABC", parent_id: 2 }, { id: 25, name: "DEF",
parent\u id
标识的子列表中,mainList中的所有元素是否至少出现一次
我目前是如何做到这一点的
let mainList = [ 2, 3, 5];
let subList = [
{
id: 23,
name: "ABC",
parent_id: 2
},
{
id: 25,
name: "DEF",
parent_id: 2
},
{
id: 26,
name: "GHI",
parent_id: 3
}
];
我想知道是否有更干净的方法来实现这一点。我要将
子列表
转换为id
的集合
,然后检查主列表
中的每个项目是否都包含在集合中:
let mainList=[2,3,5];
让子列表=[{
id:23,
名称:“ABC”,
家长编号:2
},
{
身份证号码:25,
名称:“DEF”,
家长编号:2
},
{
身份证号码:26,
名称:“GHI”,
家长编号:3
}
];
常量parentIdSet=新集合(
map({parent\u id})=>parent\u id)
);
const hasAll=mainList.every(item=>parentIdSet.has(item));
console.log(hasAll)代码>我会将子列表
转换为id
的集合
,然后检查主列表
中的每个项目是否包含在集合中:
let mainList=[2,3,5];
让子列表=[{
id:23,
名称:“ABC”,
家长编号:2
},
{
身份证号码:25,
名称:“DEF”,
家长编号:2
},
{
身份证号码:26,
名称:“GHI”,
家长编号:3
}
];
常量parentIdSet=新集合(
map({parent\u id})=>parent\u id)
);
const hasAll=mainList.every(item=>parentIdSet.has(item));
console.log(hasAll)
如果子列表
不是很大,我只会使用and:
const mainList=[2,3,5];
const subList=[{id:23,name:'ABC',parent_id:2},{id:25,name:'DEF',parent_id:2},{id:26,name:'GHI',parent_id:3}];
const matchFound=mainList.every(
mainItem=>subList.some(
subItem=>mainpitem==subItem.parent\u id
)
);
console.log(matchFound)
如果子列表
不是很大,我只会使用and:
const mainList=[2,3,5];
const subList=[{id:23,name:'ABC',parent_id:2},{id:25,name:'DEF',parent_id:2},{id:26,name:'GHI',parent_id:3}];
const matchFound=mainList.every(
mainItem=>subList.some(
subItem=>mainpitem==subItem.parent\u id
)
);
console.log(matchFound)代码>
let matchFound = true;
mainList.forEach(mainItem => {
matchFound =
matchFound &&
Boolean(
subList.find(
sub_item =>
mainItem === sub_item.parent_id
)
);
});