JavaScript函数技术求助:基于JSON查找表替换Payload中的ID为对应名称
Fixing Your JavaScript ID-to-Name Mapping Logic
Let's break down why your current code isn't working and fix it step by step:
Issues in the Original Code
- Case-sensitive variable mismatch: You defined
dataIdbut tried to usedataIDlater. JavaScript treats these as distinct variables, sodataIDwill beundefinedhere, breaking your lookup. - Using array methods on an object:
TMPmetaTable.Metadatais an object (with keys like "0", "1"), not an array. TheindexOf()method only works on arrays, so calling it here returns-1—leading to an error when you try to accessTMPmetaTable.Metadata[-1].name.
Corrected Code Option 1: Iterate Through Metadata Entries
This approach loops through each entry in the Metadata object to find the matching ID:
var TMPmetaTable = {"Metadata": {"0":{"name":"drive0_CurrentRPM","id":"101"}, "1":{"name":"drive1_CurrentRPM","id":"102"}, "2":{"name":"Battery_Voltage","id":"103"}, "3":{"name":"Battery_Current","id":"104"}} }; var dataId = msg.payload.id; // Loop through each entry to find the matching ID for (let key in TMPmetaTable.Metadata) { if (TMPmetaTable.Metadata[key].id === dataId) { msg.payload.id = TMPmetaTable.Metadata[key].name; break; // Exit loop once we find the match to save resources } } console.log(msg);
Corrected Code Option 2: Prebuild a Lookup Map (More Efficient)
If you'll be doing this mapping frequently, creating a dedicated ID-to-name map first avoids looping every time:
var TMPmetaTable = {"Metadata": {"0":{"name":"drive0_CurrentRPM","id":"101"}, "1":{"name":"drive1_CurrentRPM","id":"102"}, "2":{"name":"Battery_Voltage","id":"103"}, "3":{"name":"Battery_Current","id":"104"}} }; var dataId = msg.payload.id; // Build a reusable lookup map: key = id, value = name const idToNameMap = {}; for (let key in TMPmetaTable.Metadata) { const entry = TMPmetaTable.Metadata[key]; idToNameMap[entry.id] = entry.name; } // Replace the ID with its name (add fallback for unknown IDs if needed) if (idToNameMap[dataId]) { msg.payload.id = idToNameMap[dataId]; } else { console.warn(`No matching name found for ID: ${dataId}`); } console.log(msg);
Key Takeaways
- Always double-check variable casing in JavaScript—it's strictly case-sensitive.
- Differentiate between objects and arrays: objects use key-value pairs, while arrays use indexed elements. For repeated lookups by a specific property (like
id), a lookup map is the most efficient approach.
内容的提问来源于stack exchange,提问作者AxelD
相关产品推荐
相关产品推荐

