
learn how to cleanly rename object property names in javascript—ideal for api response transformation in low-code platforms like budibase.
learn how to cleanly rename object property names in javascript—ideal for api response transformation in low-code platforms like budibase.
When working with third-party API responses, the field names often don’t match your frontend or UI framework’s expectations (e.g., Budibase expects name and value for dropdown or chart components). Renaming keys is a common but critical data-mapping task—and doing it incorrectly (like trying to Object.assign onto a string key name) leads to silent failures, as seen in the original attempt.
The core issue in the provided code is a fundamental misunderstanding of how for...in loops and Object.assign work:
-
for (let dict in dicts)iterates over property names ("sales","city"), not values — sodictis a string, not an object. -
Object.assign(dictionary, {...})fails becausedictionaryis a string (immutable), not an object reference. - There's no actual object being transformed — just malformed mutations on primitives.
✅ Here's the correct, simple, and safe approach:
const apiResponse = {
"sales": 312,
"city": "Berlin"
};
const renamed = {
value: apiResponse.sales,
name: apiResponse.city
};
console.log(renamed);
// → { value: 312, name: "Berlin" }For dynamic or reusable renaming (especially useful in Budibase JS transforms), use a mapping configuration:
立即学习“Java免费学习笔记(深入)”;
function renameKeys(obj, keyMap) {
return Object.keys(keyMap).reduce((acc, oldKey) => {
const newKey = keyMap[oldKey];
if (obj.hasOwnProperty(oldKey)) {
acc[newKey] = obj[oldKey];
}
return acc;
}, {});
}
// Usage:
const result = renameKeys(apiResponse, {
sales: 'value',
city: 'name'
});
// → { value: 312, name: "Berlin" }? Pro Tips for Budibase Users:
- Avoid mutating the original object — always return a new object (Budibase’s JS transforms expect pure functions).
- Handle missing keys gracefully (e.g., add fallbacks like
obj[oldKey] ?? null). - If your API returns an array of such objects, wrap the rename logic in
.map():data.map(item => renameKeys(item, { sales: 'value', city: 'name' }))
❌ Never do this:
// ❌ Wrong: assigning to strings, deleting from iteration variables
for (let key in obj) { delete key['sales']; } // key is a string — deletion does nothingIn summary: rename keys by explicitly constructing a new object (or using reduce + a map), not by misusing Object.assign or for...in. Keep it functional, readable, and safe — especially in low-code environments where debugging is limited.


















