Reputation: 2116
I have the 2 following JSON files which are stored locally in my project folder.
File 1
{"_links":{"self":[{"href":"http://val1"},{"href":"http://val2"},{"href":"http://val3"},{"href":"http://val4"},{"href":"http://val5"}]}}
File 2
{"_embedded":{"accountList":[{"accountNumber":"1234","link":{"href":"http://val3/newAccount"}}]}}
I am trying to write a function which looks for matching values(specifically the 'link' values) in the 2 files. The second file however has additional url parameters.
So in summary I want to match "href":"http://val3" in file 1 with "href":"http://val3/newAccount"in file 2.
Upvotes: 0
Views: 42
Reputation: 4116
You can use the indexOf
function to tell if a string contains a certain substring. That case will reflect a match. It looks something like this
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);
});
});
Upvotes: 1
Reputation: 6015
I have kept the mapping as an object and the values would be the matching hrefs from link2. Since there could be multiple values with the same prefix, I have set it as an array. Feel free to remove the .push
and replace with =
if you want only the last matching value
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);
Upvotes: 1