我有一个html表我试图创建一个函数。我将循环遍历所有列名称,如果它们包含我的数组中的单词,我将相应地将该列值转换为格式化链接。
function createLink(field, val){
// Create a mapping of our data
var output = {
'ntid': 'https://example.com/profile/'+val,
'email': 'mailTo:' + val
};
// Test and return values
// pseudo code
if(field matches a key partially in output){
return '<a href="'+output[value]+'" target="_blank">'+[val]+'</a>';
}else{
return 'No Matches';
}
}
// Examples
createLink('NTID', 'bob'); // '<a href="https://example.com/profile/bob" target="_blank">bob</a>';
createLink('Sup NTID', 'bob'); // '<a href="https://example.com/profile/bob" target="_blank">bob</a>';
createLink('Email', 'bob@example.com'); // '<a href="mailTo:bob@example.com" target="_blank">bob@example.com</a>';
createLink('Sup Email', 'bob@example.com'); // '<a href="mailTo:bob@example.com" target="_blank">bob@example.com</a>';
我怎样才能测试该值以查看它在output
数组中是否存在部分匹配,然后返回其格式化链接?
由于这些列名是动态的并且可能随时更改,我只想测试部分单词而不是确切的字符串。
如果没有匹配,我可以返回一个占位符值,例如“No Match”。
答案 0 :(得分:1)
迭代Object.keys
并返回一个键位于&#34;字段&#34;字符串:
function createLink(field, val) {
var output = {
'ntid': 'https://example.com/profile/' + val,
'email': 'mailTo:' + val
};
for (var key of Object.keys(output))
if (field.toLowerCase().includes(key))
return `<a href="${output[key]}" target="_blank">${val}</a>`;
return 'No Matches';
}
// Examples
console.log(createLink('NTID', 'bob'));
console.log(createLink('Sup Email', 'bob@example.com'));
&#13;