@dc65k

Как заменить ключи во вложенных объектах?

Данные:

{
    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));
  • Вопрос задан
  • 135 просмотров
Решения вопроса 2
a777mp198
@a777mp198
Python developer
Ваше решение близко к решению, но в нем есть несколько ошибок:
1. Вы используете рекурсивный вызов функции solution вместо f, которую вы определили.
2. Вы присваиваете res[key] дважды: один раз перед проверкой на instanceof Object, а затем в блоке условия.
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));
Ответ написан
0xD34F
@0xD34F Куратор тега JavaScript
Рекурсия есть:

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];
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы