【问题标题】:Functional way to build array of arrays in JavaScript在 JavaScript 中构建数组数组的函数式方法
【发布时间】:2018-12-18 07:36:07
【问题描述】:

我有一个字符串,它是嵌套 JavaScript 对象中值的路径,例如:

users.userA.credentials.name

我想将此字符串拆分为其元素,然后创建一个包含所有“子路径”的数组,如下所示:

["users", "users.userA", "users.userA.credentials"]

目前我正在通过以下方式解决此问题:

const path = "users.userA.credentials.name"
const currentPath = []
const paths = []

for (const item of path.split('.')) {
  currentPath.push(item)
  paths.push([...currentPath])
}

它工作正常,但我想知道,是否有更实用的方法(使用map()filter()reduce() 或一些lodash/ramda 函数来实现相同的结果。

【问题讨论】:

  • 你也要users.userA.credentials.name作为第四项吗?
  • 'users.userA.credentials.name'.split('.').map((item,index,all)=>all.slice(0,index+1).join('.'))
  • const paths = inits("users.userA.credentials.name".split("."));。你如何实现inits(使用循环、映射、归约等)并不重要。

标签: javascript functional-programming lodash


【解决方案1】:

您可以使用Array.split()Array.map() 以更实用的方式进行操作:

const path = "users.userA.credentials.name"
const paths = path.split('.')
  .map((_, i, arr) => arr.slice(0, i + 1).join('.'));

console.log(paths);

【讨论】:

    【解决方案2】:

    您可以使用reduce 遍历子字符串并推送到累加器数组,并检查累加器的先前值(如果有)并将其与新的子字符串连接:

    const path = "users.userA.credentials.name";
    const splitPaths = path.split('.');
    const initialValue = splitPaths.shift();
    const paths = splitPaths.reduce((a, item, i) => {
      a.push(`${a[i]}.${item}`);
      return a;
    }, [initialValue]);
    console.log(paths);

    【讨论】:

      【解决方案3】:

      您可以使用array#reduce。在. 上拆分路径,然后在累加器数组中加入. 后推送子数组。

      const path = "users.userA.credentials.name",
            result = path.split('.').reduce((r, p, i, a) => {
              if(i)
                r.push(a.slice(0,i).join('.'));
              return r;
            }, []);
      console.log(result);

      【讨论】:

        【解决方案4】:

        你可以这样做

        . 分割字符串,然后通过它映射,我们根据索引连接临时数组的元素。

        let str = "users.userA.credentials.name";
        let temp = str.split('.');
        let op = temp.map((e,i)=> temp.slice(0,i+1).join('.'));
        console.log(op);

        如果你有兴趣使用正则表达式,你可以这样做

        let str = "users.userA.credentials.name";
        let temp = [];
        
        let op = str.replace(/\.|$/g,(_,offset)=>{
          temp.push(str.substr(0,offset));
          return _;
        })
        console.log(temp);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-02-14
          • 2013-07-08
          • 2020-11-11
          • 2014-02-08
          • 2013-11-22
          • 2017-10-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多