JavaScript中如何同时遍历两个数组或按间隔遍历单个数组以生成面包屑结构化数据
解决数组转面包屑结构化数据的问题
没问题,我来帮你搞定这个面包屑结构化数据的转换问题~你之前的嵌套map写法会生成所有name和url的组合(笛卡尔积),这显然不是你要的一一对应效果,所以才会出错。下面给你几种简单可靠的实现方法:
方法一:直观的for循环遍历
这种方式逻辑清晰,容易理解,适合调试和维护:
// 示例原数组 const splitBreadCrumbStructuredData = ["nameExample", "https://example.com/", "nameExampl1", "https://example1.com/", "nameExamp2", "https://example2.com/", "nameExamp3", "https://example3.com/"]; const itemListElement = []; // 每次步长为2,取成对的name和item for (let i = 0; i < splitBreadCrumbStructuredData.length; i += 2) { const name = splitBreadCrumbStructuredData[i]; const item = splitBreadCrumbStructuredData[i + 1]; // position从1开始计数 itemListElement.push({ "@type": "ListItem", position: (i / 2) + 1, name: name, item: item }); } // 组装最终的结构化数据 const breadCrumbStructuredData = { "@context": "https://schema.org", "@type": "BreadcrumbList", itemListElement: itemListElement };
方法二:函数式风格的Array.from写法
如果你偏爱简洁的函数式代码,可以用Array.from直接生成目标数组:
// 示例原数组 const splitBreadCrumbStructuredData = ["nameExample", "https://example.com/", "nameExampl1", "https://example1.com/", "nameExamp2", "https://example2.com/", "nameExamp3", "https://example3.com/"]; const itemCount = splitBreadCrumbStructuredData.length / 2; const itemListElement = Array.from({ length: itemCount }, (_, index) => ({ "@type": "ListItem", position: index + 1, name: splitBreadCrumbStructuredData[2 * index], item: splitBreadCrumbStructuredData[2 * index + 1] })); const breadCrumbStructuredData = { "@context": "https://schema.org", "@type": "BreadcrumbList", itemListElement: itemListElement };
方法三:用reduce累积处理
也可以用reduce遍历原数组,每两个元素生成一个ListItem:
// 示例原数组 const splitBreadCrumbStructuredData = ["nameExample", "https://example.com/", "nameExampl1", "https://example1.com/", "nameExamp2", "https://example2.com/", "nameExamp3", "https://example3.com/"]; const itemListElement = splitBreadCrumbStructuredData.reduce((acc, curr, index) => { // 只处理偶数索引的元素(对应name),取其下一个元素作为item if (index % 2 === 0) { acc.push({ "@type": "ListItem", position: (index / 2) + 1, name: curr, item: splitBreadCrumbStructuredData[index + 1] }); } return acc; }, []); const breadCrumbStructuredData = { "@context": "https://schema.org", "@type": "BreadcrumbList", itemListElement: itemListElement };
这三种方法都能完美实现你要的效果,你可以根据自己的代码风格选择其中一种。
内容的提问来源于stack exchange,提问作者Ejtooom
相关产品推荐
相关产品推荐

