javascript - 从字符串数组创建对象

标签 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);
}

我的实用程序函数是:

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;
  }
}

我确信有更好的解决方案,但我做不到。 所以我愿意接受任何帮助!

提前致谢!

最佳答案

您可以使用 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);

关于javascript - 从字符串数组创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55069607/

相关文章:

javascript - 在数组reduce中显式传递初始值作为未定义

javascript - 从API获取数据并在快速 View 中输出

java - 如何在Java中使用浏览器调用javascript函数?

arrays - 如何解压 slice

ruby - 是否可以使用 %w[] 速记在数组中创建一个 nil 值?

javascript - 将 Chrome 更新到版本 60 后布局过程变慢

Javascript 检查索引是否等于数字

javascript - 何时将更新推送到 REST 后端

typescript - Typescript 编译器选项 --libs 中的 es6 和 es2015 有什么区别

javascript - 将 NodeJS 项目移动到 TypeScript 的过程