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

基于映射规则转换JavaScript对象键名的技术实现求助

Solution for Renaming Object Keys Without Modifying Original Source

Got it, this is a super common scenario when working with third-party tools—you can't touch the original data structure, but you need to rename keys to make them usable. Let's break down how to solve this cleanly.

Core Idea

We'll use a key mapping object to define the old-to-new key name pairs, then write a reusable function that iterates over the original object, replaces keys using the mapping, and returns a brand new transformed object (so we never modify the original source data).

Step 1: Define Your Key Mapping

First, create an object that maps every unclear original key to its user-friendly equivalent. This makes it easy to update later if your chart plugin needs different labels.

// Define your key mappings here—customize this to match your actual keys!
const keyMapping = {
  'usrCnt': 'userCount',
  'ordAmt': 'orderAmount',
  'avgOrdVal': 'averageOrderValue',
  'activeDt': 'activeDate',
  'newUsrCnt': 'newUserCount',
  'repeatOrdRate': 'repeatOrderRate'
};

Step 2: Write the Transformation Function

Option 1: For Flat Objects (No Nested Data)

If your source object is simple with no nested objects or arrays, use this concise version:

function transformFlatData(originalData, keyMap) {
  // Convert original object to entries, map keys, then convert back to object
  return Object.fromEntries(
    Object.entries(originalData).map(([oldKey, value]) => [
      keyMap[oldKey] || oldKey, // Use mapped key if exists, else keep original
      value
    ])
  );
}

Option 2: For Nested Objects/Arrays (Universal Solution)

If your source data has nested objects or arrays (super common in real-world data), use this recursive version to handle all levels:

function transformNestedData(originalData, keyMap) {
  // Handle arrays: recursively transform each item
  if (Array.isArray(originalData)) {
    return originalData.map(item => transformNestedData(item, keyMap));
  }

  // Handle non-objects (strings, numbers, booleans, null)
  if (typeof originalData !== 'object' || originalData === null) {
    return originalData;
  }

  // Initialize new transformed object
  const transformed = {};

  // Iterate over original object keys
  for (const oldKey in originalData) {
    if (originalData.hasOwnProperty(oldKey)) {
      // Get the new key (fallback to original if no mapping exists)
      const newKey = keyMap[oldKey] || oldKey;
      // Recursively transform the value (in case it's an object/array)
      transformed[newKey] = transformNestedData(originalData[oldKey], keyMap);
    }
  }

  return transformed;
}

How to Use It

Here's a full example with sample source data:

// Original data from Source1—you never modify this!
const sourceData = {
  usrCnt: 1200,
  ordAmt: 45000,
  avgOrdVal: 37.5,
  activeDt: '2024-05-20',
  userMetrics: {
    newUsrCnt: 200,
    repeatOrdRate: 0.65
  },
  recentOrders: [
    { ordId: 'ORD123', ordAmt: 95 },
    { ordId: 'ORD124', ordAmt: 42 }
  ]
};

// Transform the data for your chart plugin
const chartReadyData = transformNestedData(sourceData, keyMapping);

console.log(chartReadyData);

Output Preview

The transformed object will have clear keys like userCount, orderAmount, and even nested keys like newUserCount will be renamed correctly. Arrays of objects are also processed recursively.

Key Benefits

  • Non-destructive: The original source data remains untouched (critical since you can't modify Source1's structure).
  • Scalable: Update the keyMapping object anytime without changing the transformation logic.
  • Flexible: Works for both flat and deeply nested data structures.

内容的提问来源于stack exchange,提问作者SBB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:05:16