自定义数组到自定义对象?

时间:2018-08-03 01:57:54

标签: javascript typescript

我想将此数组转换为如下所示的对象。

let a = ["CBSE/X","HOS/A/A1","FOOD/S"]

结果应该类似于:

{  
   CBSE : ["X"],
   HOS  : [{ A : ["A1"] }],
   FOOD : ["S"],
}

我尝试过的东西

.split("/")

试图拆分每个对象等等,但是无法前进。

4 个答案:

答案 0 :(得分:1)

一种方法是在split内使用reduceRight / reduce

let a = ["CBSE/X","HOS/A/A1","FOOD/S"]

let r = a.reduce((a, c) => 
    Object.assign(a, 
      c.split('/') 
       .reduceRight((a, c) => a ? [{[c]: a}] : [c], null)[0]
    )
,{})


console.log(r)

答案 1 :(得分:0)

如果约束仅是您在问题中概述的约束,并且没有任何对象具有多个属性,并且数组中的任何字符串都不会有多个/,那么您可以使用reduce

let a = ["CBSE/X","HOS/A/A1","FOOD/S"];

var o = a.reduce((obj, str) => {
  var items = str.split("/");
  var key = items[0];
  var val = items.length > 2 ? { [items[1]] : [items[2]] } : items[1];
  obj[key] = [val];
  return obj;
  }, {});
  
console.log(o);

答案 2 :(得分:0)

这是TypeScript中使用递归解析的解决方案:

String createTargetTableSql = "CREATE TABLE IF NOT EXISTS " + TARGET_TABLE_NAME +
            "( " +
            " `case_number` " +
            " `extra_info` string "+
            " ) " +
            " PARTITIONED BY (`dt` STRING) " +
            " STORED AS ORC";

答案 3 :(得分:0)

这是另一回事,它是迭代的,基本上是在子链中排队并进行格式化:

let a = ["CBSE/X","HOS/A/A1","FOOD/S"];

const munge = a => 
  a.reduce((res, e) => {
    e = e.split("/");
    let a = [];
    res[e.shift()] = a;

    while (e.length) {
      const newKey = e.shift();
      a.push(newKey);

      if (e.length) {
        a[0] = {[newKey] : []};
        a = a[0][newKey];
      }
    }
    
    return res;
  }, {})
;

console.log(munge(a));