从字符串数组创建对象

时间:2019-03-08 19:15:42

标签: javascript arrays typescript object

我正在尝试从字符串数组创建对象。

我有这个字符串数组:

let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world'];

我想要一个这样的对象:

{
  origin : ['develop', 'master'],
  toto : ['branch'],
  tata : ['hello', 'world']
}

所以暂时,我做到了:

let Obj = {};
let RemoteObj = {};
for (let CurrentIndex = 0; CurrentIndex < BaseArray.length; CurrentIndex++) {
    let Splits = BaseArray[CurrentIndex].split('/');
    if (Splits[0] && Splits[1]) {
        Obj[Splits[0]] = Splits[1].trim();
    }

    if (this.isObjectEmpty(RemoteObj)) {
        RemoteObj = Obj;
    } else {
        RemoteObj = this.mergeObjects(RemoteObj, Obj);
    }
    console.log(RemoteObj);
}

我的utils函数是:

mergeObjects(...objs) {
  let Result = {}, Obj;

  for (let Ind = 0, IndLen = objs.length; Ind < IndLen; Ind++) {
    Obj = objs[Ind];

    for (let Prop in Obj) {
      if (Obj.hasOwnProperty(Prop)) {
        if (!Result.hasOwnProperty(Prop)) {
          Result[Prop] = [];
        }
        Result[Prop].push(Obj[Prop]);
      }
    }
  }

  return Result;
}

isObjectEmpty(Obj) {
  for (let Key in Obj) {
    if (Obj.hasOwnProperty(Key)) {
      return false;
    }
    return true;
  }
}

我确定有更好的解决方案,但是我做不到。 因此,我愿意提供任何帮助!

预先感谢!

5 个答案:

答案 0 :(得分:6)

您可以使用Array.reduce()来创建对象,方法是将每个字符串拆分为键和值,如果键不存在则为该键分配一个空数组,然后将值推入数组:

const BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world'];

const result = BaseArray.reduce((r, str) => {
  const [key, value] = str.split('/');
  
  if(!r[key]) r[key] = [];
  
  r[key].push(value);
  
  return r;
}, {});

console.log(result);

答案 1 :(得分:3)

您可以使用splitreduce

let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world'];

let op = BaseArray.reduce((op, inp) => {
  let [key, value] = inp.split('/')
  op[key] = op[key] || []
  op[key].push(value)
  return op
},{})

console.log(op)

答案 2 :(得分:3)

您可以使用Array.reduce()进行此操作。在reduce的每次迭代中,您可以将字符串除以/并将第一个元素用作新对象上的key,然后将第二个元素放在与该key关联的数组上:

let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world'];

let res = BaseArray.reduce((acc, curr) =>
{
    let [k, v] = curr.split("/");
    (acc[k] = acc[k] || []).push(v);
    return acc;
}, {});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 3 :(得分:2)

您可以使用reduce方法来构建对象。

let baseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world'];

let baseobj = baseArray.reduce((acc, curr) => {
   let items = curr.split('/');
   let key = items[0];
   let value = items[1];
   
   if(acc[key] === undefined) {
      acc[key] = [value] 
   } else {
      acc[key] = [...acc[key], value];
   }
   
   return acc;
}, {});

console.log(baseobj);

答案 4 :(得分:1)

您可以使用reducesplit字符串来产生数组。然后,使用数组索引0处的元素创建object键。并将其余的值推入数组

let BaseArray = ['origin/develop', 'origin/kit/sub', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world'];

let newArray = BaseArray.reduce(function(acc, curr) {
  let splitCurr = curr.split('/');
  if (!acc[splitCurr[0]]) {
    acc[splitCurr[0]] = []
  }
  for (let i = 1; i < splitCurr.length; i++) {
    acc[splitCurr[0]].push(splitCurr[i])

  }
  return acc;
}, {});

console.log(newArray)