{ 'старый ключ': 'новый ключ' }
:const keys = {
x: 'a',
y: 'b',
z: 'c',
};
const renameKeys = (obj, keys) =>
Object.fromEntries(Object
.entries(obj)
.map(([ k, v ]) => [ Object.hasOwn(keys, k) ? keys[k] : k, v ])
);
// или
const renameKeys = (obj, keys) =>
Object.keys(obj).reduce((acc, k) => (
acc[keys[k] ?? k] = obj[k],
acc
), {});
const newArr = arr.map(n => renameKeys(n, keys));
function renameKeys(keys, obj) {
for (const k in keys) {
if (obj.hasOwnProperty(k)) {
obj[keys[k]] = obj[k];
delete obj[k];
}
}
}
arr.forEach(renameKeys.bind(null, keys));
const data3 = [
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
{ x: 7, y: 8, z: 9 },
];
const changeKeyses = (arr, new_keyses) => arr.map(obj => {
Object.keys(obj).forEach((key, i) => {
let new_key = new_keyses[i];
if (new_key !== undefined) {
let val = obj[key];
delete obj[key];
obj[new_key] = val;
}
});
return obj;
});
console.log(changeKeyses(data3, ["a", "b", "c"]));
console.log(changeKeyses(data3, ["a", "b"]));
console.log(changeKeyses(data3, ["a"]));
const replaceKeys = (value, replacer) =>
value instanceof Object
? value instanceof Array
? value.map(n => replaceKeys(n, replacer))
: Object.fromEntries(Object
.entries(value)
.map(n => [ replacer(n[0]), replaceKeys(n[1], replacer) ])
)
: value;
const newObj = replaceKeys(obj, k => `${k}_upd`);
function replaceKeys(value, replacer) {
const stack = [];
const clones = new Map;
const getClone = val => val instanceof Object
? (clones.has(val) || stack.push([ val, clones.set(val, val.constructor()).get(val) ]),
clones.get(val))
: val;
for (getClone(value); stack.length;) {
const [ source, target ] = stack.pop();
const isArray = Array.isArray(source);
for (const k in source) if (Object.hasOwn(source, k)) {
target[isArray ? k : replacer(k)] = getClone(source[k]);
}
}
return getClone(value);
}