{
foo_bar: {
bar_baz: 2
},
a: [
{
foo_bar: 4
},
{},
1,
2,
3
]
}
{
foo_bar_upd: {
bar_baz_upd: 2
},
a_upd: [
{
foo_bar_upd: 4
},
{},
1,
2,
3
]
}
const f = (obj) => {
const res = {}
const array = Object.keys(obj)
for (let i = 0; i < array.length; i++) {
const current = array[i]
const key = `${current}_upd`
res[key] = obj[current]
if (obj[current] instanceof Object) {
res[key] = solution(obj[current])
} else {
res[key] = obj[current]
}
}
return res
}
console.log(f(data));
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);
}
const f = (obj) => {
const res = {};
for (let key in obj) {
const newKey = `${key}_upd`;
if (Array.isArray(obj[key])) {
res[newKey] = obj[key].map((el) => {
return el instanceof Object ? f(el) : el;
});
} else {
res[newKey] =
obj[key] instanceof Object ? f(obj[key]) : obj[key];
}
}
return res;
};
console.log(f(data));