You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 dataId but tried to use dataID later. JavaScript treats these as distinct variables, so dataID will be undefined here, breaking your lookup.
  • Using array methods on an object: TMPmetaTable.Metadata is an object (with keys like "0", "1"), not an array. The indexOf() method only works on arrays, so calling it here returns -1—leading to an error when you try to access TMPmetaTable.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:47:29