angular - 在 2 个单独的 JSON 文件中查找匹配值
问题描述
我有以下 2 个 JSON 文件,它们本地存储在我的项目文件夹中。
文件 1
{"_links":{"self":[{"href":"http://val1"},{"href":"http://val2"},{"href":"http://val3"},{"href":"http://val4"},{"href":"http://val5"}]}}
文件 2
{"_embedded":{"accountList":[{"accountNumber":"1234","link":{"href":"http://val3/newAccount"}}]}}
我正在尝试编写一个在 2 个文件中查找匹配值(特别是“链接”值)的函数。然而,第二个文件有额外的 url 参数。
所以总而言之,我想将文件 1 中的“href”:“http:// val3 ”与文件 2中的“href”:“ http://val3/newAccount ”相匹配。
解决方案
我将映射保留为一个对象,并且值将是来自 link2 的匹配 href。由于可能有多个具有相同前缀的值,因此我将其设置为数组。如果您只想要最后一个匹配值 ,请随意删除.push
并替换为=
let file1 = {"_links":{"self":[{"href":"http://val1"},{"href":"http://val2"},{"href":"http://val3"},{"href":"http://val4"},{"href":"http://val5"}]}}
let file2 =
{"_embedded":{"accountList":[{"accountNumber":"1234","link":{"href":"http://val3/newAccount"}}]}}
let href1 = file1._links.self.map(i => i.href);
let href2 = file2._embedded.accountList.map(i=> i.link.href);
let mapping = href2.reduce((acc,ref) => {
let prefix = href1.find(_ref => ref.startsWith(_ref));
if(prefix){
if(!acc[prefix]) acc[prefix] = [];
acc[prefix].push(ref);
}
return acc;
},{});
console.log(mapping);
推荐阅读
- python - 如何通过 ArcPy 使用光标遍历列表、进行属性和空间选择以及填充字段
- python-3.x - 导出为 CSV,它会覆盖或附加每个新行的标题和行
- powershell - 如何从 Powershell 中的 forEach-Object 循环返回文件名?
- jquery - 使用运算符验证jQuery中是否存在数组?
- vue.js - 如何在 VUE 组件上安装 masonry-layout
- r - 如果函数在 R 中返回小于某个数字,则运行计数
- azure - 构建和推送到 Azure 容器注册表的 VS 代码问题
- anylogic - Anylogic系统动力学固定时间步长?
- java - 列出打印奇怪的值而不是字符串
- python - 如何使用 python 在我的 github 帐户上创建远程 git 存储库或使用 python 将本地 git repo 推送到我的 github 帐户?