You need to enable JavaScript to run this app. 如何通过REST API比对两个SharePoint列表并筛选匹配项展示
优惠活动
大模型
产品
解决方案
定价
更多

如何通过REST API比对两个SharePoint列表并筛选匹配项展示

SharePoint Online 双列表字段比对匹配实现方案

现有代码的核心问题

你目前的代码逻辑虽然分别写了两个列表的请求,但实际运行都会出问题,根源在这几点:

  • 两次AJAX请求中重名定义了onSuccess、onError,ListAItems、ListBItems是函数局部作用域变量,根本跨请求存不住结果
  • AuthorId是整数类型,你在筛选值外面加了多余的单引号,会导致REST接口返回类型不匹配的400错误
  • 两个AJAX请求是并行发起的,没有等待两个请求都返回完成的校验机制,就算没有报错,比对逻辑也拿不到完整的两个列表的数据
  • 你给单选项类型列加的$expand参数是适配人员/查找类字段的,选项列本身自带Value属性存选项文本,多余的expand会导致取值为undefined

核心实现思路

整个流程不需要额外发多余的请求,基于现有拿到的数据就能完成高效比对:

  1. 利用页面上下文自带的_spPageContextInfo.userId直接取当前用户ID,不需要额外调接口查用户信息
  2. 修正ListA的REST请求参数,正确带筛选条件拉取当前用户创建的条目
  3. 等ListA、ListB两个请求全部成功返回后,再做字段比对
    • 先把ListA里所有条目的Position和Location值拼接成唯一匹配键,存在JS对象集合里
    • 遍历ListB的所有条目,同样拼接匹配键,只要键存在于ListA的集合里,就作为匹配结果保留
  4. 把匹配结果直接传入jQuery DataTable组件渲染即可

比对效率优化:如果用双重循环逐条目和逐字段比对,当列表条目到千级规模时,时间复杂度是O(n²),会出现明显的页面卡顿;用拼接键存集合的方式,两次遍历总时间复杂度是O(n),哪怕拉取5000条ListB数据也不会有性能问题。

关键比对代码片段

// 收集ListA的所有匹配键,O(1)时间复杂度查匹配
const matchKeySet = {};
ListAItems.forEach(item => {
    const posVal = item.Position?.Value?.trim() || '';
    const locVal = item.Location?.Value?.trim() || '';
    // 用竖线拼接两个字段值作为唯一键,避免单字段值重复导致的误匹配
    const matchKey = `${posVal}|${locVal}`;
    matchKeySet[matchKey] = true;
});

// 遍历ListB筛选匹配项
const matchedResults = [];
ListBItems.forEach(item => {
    const posVal = item.Position?.Value?.trim() || '';
    const locVal = item.Location?.Value?.trim() || '';
    const matchKey = `${posVal}|${locVal}`;
    if(matchKeySet[matchKey]) {
        matchedResults.push({
            Position: posVal,
            Location: locVal
        })
    }
})

注意:如果列表条目为空,取字段值的时候一定要加可选链判断,避免因为字段不存在导致脚本报错中断

完整可运行代码

<input type="button" id="onClick" value="Get Matches" /> 
<table id="matchDataTable" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Position</th>
            <th>Location</th>
        </tr>
    </thead>
</table>

<script>
$(function(){
    // 提前初始化空的DataTable实例
    let matchTable = $('#matchDataTable').DataTable({
        columns: [
            { data: "Position" },
            { data: "Location" }
        ]
    });

    $("#onClick").click(function(){
        const userId = _spPageContextInfo.userId; 
        
        // 发起ListA请求:修正筛选条件,去掉类型错误的引号
        const listARequest = $.ajax({
            url: `${_spPageContextInfo.webAbsoluteUrl}/_api/Web/Lists/GetByTitle('ListA')/items?$select=Id,Position,Location&$top=5000&$filter=AuthorId eq ${userId}`,
            type: "GET",
            headers: {
                "accept":"application/json; odata=verbose"
            }
        });
        
        // 发起ListB请求:去掉不需要的expand参数
        const listBRequest = $.ajax({
            url: `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('ListB')/items?$select=Id,Position,Location&$top=5000`,
            type: "GET",
            headers: {
                "accept":"application/json; odata=verbose"
            }
        });

        // 等待两个请求全部完成再执行后续逻辑
        $.when(listARequest, listBRequest).done(function(listARes, listBRes){
            const ListAItems = listARes[0].d.results;
            const ListBItems = listBRes[0].d.results;

            // 构建匹配键集合
            const matchKeySet = {};
            ListAItems.forEach(item => {
                const pos = item.Position?.Value?.trim() || '';
                const loc = item.Location?.Value?.trim() || '';
                matchKeySet[`${pos}|${loc}`] = true;
            });

            // 筛选ListB中的匹配条目
            const matchedData = ListBItems.reduce((result, item) => {
                const pos = item.Position?.Value?.trim() || '';
                const loc = item.Location?.Value?.trim() || '';
                if(matchKeySet[`${pos}|${loc}`]) {
                    result.push({ Position: pos, Location: loc });
                }
                return result;
            }, []);

            // 清空表格原有数据,加载新的匹配结果
            matchTable.clear().rows.add(matchedData).draw();
        }).fail(function(error){
            console.error("列表数据请求失败:", error);
        });
    });
});
</script>

内容的提问来源于stack exchange,提问作者Sidd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.28 16:54:03