Create an object from a string array

Nul*_*lji 4 javascript arrays object typescript

I'm trying to create an object from a string array.

I've this string array :

let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world'];
Run Code Online (Sandbox Code Playgroud)

and I would like to have an object like that :

{
  origin : ['develop', 'master'],
  toto : ['branch'],
  tata : ['hello', 'world']
}
Run Code Online (Sandbox Code Playgroud)

So for the moment, I did this :

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);
}
Run Code Online (Sandbox Code Playgroud)

And my utils functions are :

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

I'm sure there is a better solution to do it but I can't do it. So I'm open to any help !

Thanks by advance !

Ori*_*ori 6

You can use Array.reduce() to create the object by splitting each string to the key and value, assigning an empty array to the key if it doesn't exist, and pushing the value to the array:

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);
Run Code Online (Sandbox Code Playgroud)