Я надеюсь, вы можете понять это сейчас?

сивом

['/social/swipes/women', '/social/swipes/men', '/upgrade/premium'];

Я хотел бы построить объект карты, который выглядит следующим образом:

{
    'social': {
        swipes: {
            women: null,
            men: null
        }
    },
    'upgrade': {
        premium: null
    }
}

const menu = ['/social/swipes/women', '/social/likes/men', '/upgrade/premium'];
const map = {};

const addLabelToMap = (root, label) => {
  if(!map[root]) map[root] = {};
  if(!map[root][label]) map[root][label] = {};
}

const buildMenuMap = menu => {
  menu
    // make a copy of menu
    // .slice returns a copy of the original array
    .slice()
    // convert the string to an array by splitting the /'s
    // remove the first one as it's empty
    // .map returns a new array
    .map(item => item.split('/').splice(1))
    // iterate through each array and its elements
    .forEach((element) => {
      let root = map[element[0]] || "";

      for (let i = 1; i < element.length; i++) {
        const label = element[i];
        addLabelToMap(root, label)
        // set root to [root][label]
        //root = ?
        root = root[label];
      }
    });
}

buildMenuMap(menu);

console.log(map);

Но я не уверен, как изменить значениеroot.

Что я установилroot чтобы это рекурсивно вызываетaddLabelToMap с участием

'[social]', 'swipes' => '[social][swipes]', 'women' => '[social][swipes]', 'men'?

Я использовалroot = root[element] но это дает ошибку.

Альтернативные решения были бы хороши, но я хотел бы понять, почему это не работает в принципе.

Ответы на вопрос(8)

Ваш ответ на вопрос