首页 > 解决方案 > 在 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 ”相匹配。

标签: angulartypescript

解决方案


我将映射保留为一个对象,并且值将是来自 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);


推荐阅读