我有本地存储在我的项目文件夹中的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个文件的功能,其查找匹配值(特别是“链接”值)。然而,第二个文件还有其他网址参数。
因此,在总结我想匹配的“href”:在文件1的“href”“http://val3”:“http://val3/newAccount”文件2。
我一直映射作为一个对象,并且值将是从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);
您可以使用indexOf
函数来判断一个字符串包含一定子。这种情况下,将体现出比赛。它看起来是这样的
const objOne = {"_links":{"self":[{"href":"http://val1"},{"href":"http://val2"},{"href":"http://val3"},{"href":"http://val4"},{"href":"http://val5"}]}};
const objTwo = {"_embedded":{"accountList":[{"accountNumber":"1234","link":{"href":"http://val3/newAccount"}}]}};
objTwo._embedded.accountList.forEach(longLink => {
objOne._links.self.map(l => l.href).forEach(shortLink => {
if (longLink.link.href.indexOf(shortLink) != -1)
console.log('Found match!', longLink);
});
});
你可以试试这个,
// JSON 1
let json1 = {
_links:{
self:[
{href:"http://val1"},
{href:"http://val2"},
{href:"http://val3"},
{href:"http://val4"},
{href:"http://val5"}
]
}
}
// JSON 2
let json2 = {
_embedded:{
accountList:[
{accountNumber:"1234",link:{href:"http://val3/newAccount"}}
]
}
}
// Iterate through account list
for (let account of json2._embedded.accountList){
// Search in links list
if(json1._links.self.find(i=>account.link.href.startsWith(i.href))){
console.log("Match found")
}else{
console.log("No match found")
}
}