【问题标题】:Mapping array of strings into array of specific object将字符串数组映射到特定对象数组
【发布时间】:2021-07-30 09:21:10
【问题描述】:

我在将字符串数组转换为 url 路径对象(用于面包屑)时遇到问题

我有这个数组:

const array = ['visit', 'schedule', 'validator']

我尝试了什么:

  const routeArray = array.map((b) => ({
    label: b,
    route: `/${b}`,
  }))
  console.log(routeArray)

结果:

   [  
     {label: "visit", route: "/visit"},
     {label: "schedule", route: "/schedule"},
     {label: "validator", route: "/validator"},
   ] 

我想要达到的目标:

  [
    {label: "visit", route: "/visit"},
    {label: "schedule", route: "/visit/schedule"},
    {label: "validator", route: "/visit/schedule/validator"}
  ]

有什么帮助吗?

【问题讨论】:

  • 您能分享一下您到目前为止所尝试的方法吗?请注意,在这里提问之前,希望人们make some effort自己解决问题。
  • @secan 当然!我编辑了帖子

标签: javascript arrays ecmascript-6


【解决方案1】:

在遍历数组时连接字符串:

const array = ['visit', 'schedule', 'validator'];

let route = "";

const result = array.map(label => {
    route += '/' + label;
    return { label, route };
});

【讨论】:

  • 不错!感谢分享
【解决方案2】:

Array.prototype.map()Array.prototype.slice()Array.prototype.join() 可以成为你最好的朋友,在这里:

const input = ['visit', 'schedule', 'validator'];

const output = input.map((item, index) => {
  return {
    label: item,
    route: '/' + input.slice(0, index + 1).join('/')
  }
});

// test
console.log(output);

【讨论】:

  • 简单有效!感谢您的回答
【解决方案3】:

请检查一下,如果这是您要找的,请告诉我:

const array = ['visit', 'schedule', 'validator'] 

const newArray = array.map((entry, index) => {
  const route = [];
  
  for (let i = 0; i < index + 1; i++) {
    route.push(array[i]);
  }
  
  return {
    label: entry,
    route: route.join('/'),
  };
});

console.log(newArray);

在这种方法中,我循环遍历current elementarrayas many 元素as the orderpushing 它们进入route array。在创建对象属性时,我joinelements of route用'/'分隔。

【讨论】:

    【解决方案4】:

    下面是我们如何使用 reduce 方法做到这一点:

    const arr = ["visit", "schedule", "validator"];
    const res = arr.reduce((acc, curr, idx, self) => {
    
        // Our route property of our needed data structure
        const route = `/${self.slice(0, idx)}${idx > 0 ? "/" + curr : curr}`;
    
        // Our new object
        const obj = { label: curr, route };
        return [...acc, obj];
    }, []);
    
    console.log(res);
    

    【讨论】:

    • 预期输出与输入一一匹配;在我看来,在这种情况下使用 Array.prototype.reduce() 会增加不必要的复杂性。
    • 感谢分享!
    【解决方案5】:

    可以使用 for 循环来完成。您需要有一个变量来跟踪您的 incrementing 路由并在循环迭代中持续存在。

    const array = ['visit', 'schedule', 'validator'];
    
    let ansArray = [];
    let incrVal = '';
    for(let i = 0 ; i < array.length; i++){
    let ans = incrVal + '/' + array[i];
    ansArray.push({'label' : array[i], 'route' : ans});
    incrVal = ans;
    }
    
    console.log(ansArray);

    【讨论】:

      【解决方案6】:

      const array = ['visit', 'schedule', 'validator'];
      
      const results = array.map((item, index, arr) => {
        
        return {
          label: item,
          route: '/' + arr.slice(0, index + 1).join('/'),
        };
      });
      
      console.log(results);

      【讨论】:

        【解决方案7】:

        使用reduce数组方法

        const array = ["visit", "schedule", "validator"];
        const res = array.reduce((acc, curr, idx, arr) => {
          acc.push({
            label: curr,
            route:'/'+ arr.slice(0, idx + 1).join('/')
          })
          return acc;
        }, []);
        
        console.log(res);

        【讨论】:

          【解决方案8】:

          我认为这是执行此操作的最短方法:

          const input = ["visit", "schedule", "validator"];
          const res = input.map((label, i, arr) => ({
            label,
            route: '/' + arr.slice(0, i + 1).join("/")
          }));
          
          console.log(input);
          console.log(res);

          【讨论】:

            猜你喜欢
            • 2018-05-29
            • 1970-01-01
            • 2012-01-23
            • 2021-11-15
            • 2015-07-16
            • 1970-01-01
            • 2014-10-31
            • 2021-11-23
            • 1970-01-01
            相关资源
            最近更新 更多