A really easy way to change the keys dynamically without having to map the new key values could work like this :
const tab = { abc: 1, def: 40, xyz: 50 };
const changeString = (s) => s.split('').join('_');
Object.entries(tab).reduce((acc, [k, v]) => ({ ...acc, [changeString(k)]: v }), {})
// Output: {a_b_c: 1, d_e_f: 40, x_y_z: 50}
It uses Object.entries
but you can easily swap it over to Object.keys
like this:
Object.keys(tab).reduce((acc, k) => ({ ...acc, [changeString(k)]: tab[k] }), {})
Advanced: Nested objects
If you have nested objects and want to cycle through all the keys, you could try this:
const changeString = (s) => s.split('').join('_');
const isArray = (a) => Array.isArray(a);
const isObject = (o) => o === Object(o) && !isArray(o) && typeof o !== 'function';
const keyChanger = (o) => {
if (isObject(o)) {
return Object.entries(o).reduce((acc, [k, v]) => ({ ...acc, [changeString(k)]: keyChanger(v) }), {})
} else if (isArray(o)) {
return o.map((i) => keyChanger(i));
}
return o;
};
And you call it by simply doing this:
const tab2 = { abc: 1, def: 40, xyz: { hij: 12, klm: [{ nop: 43 }, { qrs: 65 }]}}
keyChanger(tab2)
// Output: { a_b_c: 1, d_e_f: 40, x_y_z: { h_i_j: 12, k_l_m: [{ n_o_p: 43 }, { q_r_s: 65 }]}}