Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查由标识符标识的子数组内主数组中的所有元素是否至少出现一次_Javascript_Arrays_Loops_Object_Foreach - Fatal编程技术网

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
                )
            );
    });