将字符串转换为嵌套对象和数组

问题描述 投票:-1回答:1

[我在一个项目中,前一个家伙做了一些奇怪的路由,基本上我从有满足感的条中以字符串的形式被插入到数组["/api/", "/docs/getting-started/", "/docs/, "/plugin/", "/plugin/user/", "/plugin/profile/"......]

现在我需要将其转换为数组形式

let cleanedSidebarContents = [{
              title:null,
              pages:[
                     {title:"api",
                      path:"/api/"
                      },
                     {title:"docs",
                      path:"/docs/"
                      },
                      {title:"plugin",
                      path:"/plugin/"
                      },
                     ]
               },
             {
              title:"plugin",
              pages:[
                     {title:"user",
                      path:"/plugin/user/"
                      },
                     {title:"profile",
                      path:"/plugin/profile/"
                      },
                     ]
               },
              {
              title:"docs",
              pages:[
                     {title:"getting-started",
                      path:"/plugin/getting-started/"
                      },
                     ]
               }
]

所以目前我正在做什么-

 //-------Format sidebar data--------------->
    let cleanedSidebarContents = [];
    (function cleanSidebarContents() {

        let sideBarContentsContentful = [];
        cleanContentfulEdges.forEach(edge => {
            let slug = edge.node.slug;
            //split string into titles and remove empty spaces
            let routeMapArray = slug.split("/").filter(x => x != "");
            if (routeMapArray.length > 1) {
                sideBarContentsContentful.push({
                    title: routeMapArray[0],
                    page: {
                        title: routeMapArray[routeMapArray.length - 1],
                        path: edge.node.slug
                    }
                });
            } else {
                sideBarContentsContentful.push({
                    title: null,
                    page: {
                        title: routeMapArray[routeMapArray.length - 1],
                        path: edge.node.slug
                    }
                });
            }
        });

        let titles = [];
        for (let i = 0; i < sideBarContentsContentful.length; i++) {
            titles.push(sideBarContentsContentful[i].title);
        }
        //clean duplicate entries
        titles = titles.filter(function (item, index, inputArray) {
            return inputArray.indexOf(item) === index;
        });
        titles.sort();

        titles.map(item => {
            cleanedSidebarContents.push({
                title: item,
                pages: []
            })
        });

        sideBarContentsContentful.forEach(item => {
            for (let i = 0; i < cleanedSidebarContents.length; i++) {
                if(cleanedSidebarContents[i].title === item.title){
                    cleanedSidebarContents[i].pages.push(item.page)
                }
            }
        });
    }());
    //----------------------------------------->

我首先拆分所有字符串,然后将标题放在titles数组中,然后删除重复项并相应地映射数据。

我只是觉得这是非常糟糕的代码,还有一种更好的方法我无法弄清楚。

javascript arrays object contentful
1个回答
0
投票

您可以创建一个mapper对象,该对象使用root关键字映射输出中的对象。使用正则表达式获取路径中的字符。如果存在一个匹配项,则它属于默认的null对象。否则,将匹配项中的第一个键用作输出中的键

const input = ["/api/", "/docs/getting-started/", "/docs/", "/plugin/", "/plugin/user/", "/plugin/profile/"]

const mapper = {},
      output = [];

for (const path of input) {
  let matches = path.match(/[^\/]+(?=\/)/g),
      mapperKey = null;

  if (matches.length > 1)
    mapperKey = matches[0];

  if (!mapper[mapperKey]) {
    mapper[mapperKey] = { title: mapperKey, pages: [] };
    output.push(mapper[mapperKey]);
  }

  const title = matches.pop();
  mapper[mapperKey].pages.push({ title, path })
}

console.log(output)
© www.soinside.com 2019 - 2024. All rights reserved.