精慕HU
2023-04-27 10:43:42
我設置了 10 個“標簽”,每個都有一個 ID(格式:00:00:00:xx:xx:xx)和 translatedID(格式:TXT)。我得到字符串列表違反標簽,我想將其從 translatedID 轉換為 ID。我有一個定義值的映射:Map(10) { '00:00:00:02:28:47' => 'T7T', '00:00:00:02:89:70' => 'T3T', '00:00:00:02:89:51' => 'T4T', '00:00:00:02:27:bd' => 'T5T', '00:00:00:02:89:31' => 'T6T', '00:00:00:02:89:a0' => 'T1T', '00:00:00:02:89:af' => 'T2T', '00:00:00:02:89:4d' => 'T9T', '00:00:00:02:89:28' => 'T10T', '00:00:00:02:89:a1' => 'T8T'}例子:input = 'T4T____T5T____T2T____T10T____T6T____'(desired) output = '00:00:00:02:89:51, 00:00:00:02:27:bd, 00:00:00:02:89:af, 00:00:00:02:89:28, 00:00:00:02:89:31'我的第一個想法是遍歷映射中的每個值,查看它是否存在于輸入中,如果存在,則將相應的 ID 添加到輸出中。但由于不必要的額外循環,這不是最優的。有什么建議么?此外,我的代碼使用全局變量來定義地圖變量。我知道這是不受歡迎的,我有更好的方法嗎?我的代碼格式如下:let dict = new Map()function customQueryString() { return new Promise((resolve, reject) => { client.query(query, (err, res) => { res.rows.forEach(psqltag => { dict.set(psqltag.m_violator_tag, psqltag.m_translatedid) }); resolve(queryStringAddition) // defined elsewhere doesnt matter for this problem }) })}function loopingQueryFunction(loopQuery) { client.query(loopQuery, (err, res) => { res.rows.forEach(tag => { input = tag.violating_tags // where the input string is found output = ??? // where the translation needs to happen } }}async function asyncCall() { let qStringAddition = await customQueryString(); loopQuery = loopQuery + qStringAddition for (let i = 0; i< 100; i++) { console.log("loop " + i) await delay(1000) loopingQueryFunction(loopQuery) }}
1 回答

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
您可以使用正則表達式來獲取所有已翻譯的 ID。讓我們假設它們都是T<number>T格式的,這看起來是真的。
const input = 'T4T____T5T____T2T____T10T____T6T____';
const dictEntries = [...dict.entries()].map(([id, translatedId]) => ({id, translatedId}));
const output = input
.match(/T\d+T/g)
.map(translatedId => dictEntries.find(entry => entry.translatedId === translatedId))
.filter(entry => entry !== undefined)
.map(entry => entry.id);
// ["00:00:00:02:89:51", "00:00:00:02:27:bd", "00:00:00:02:89:af", "00:00:00:02:89:28", "00:00:00:02:89:31"]
output.join(', ')如果你想要它作為逗號分隔的字符串,你可以得到。
添加回答
舉報
0/150
提交
取消