{
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 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));
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 result = [];
const stack = [];
for (
let i = 0, source = [ [ 0, value ] ], target = result;
i < source.length || stack.length;
i++
) {
if (i === source.length) {
[ i, source, target ] = stack.pop();
} else {
const [ k, v ] = source[i];
const isObject = v instanceof Object;
const newK = target instanceof Array ? k : replacer(k);
target[newK] = isObject ? v.constructor() : v;
if (isObject) {
stack.push([ i, source, target ]);
[ i, source, target ] = [ -1, Object.entries(v), target[newK] ];
}
}
}
return result[0];
}