Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object from a string array

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'];

and I would like to have an object like that :

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

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

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

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 !

like image 322
Nulji Avatar asked Dec 05 '22 10:12

Nulji


2 Answers

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);
like image 65
Ori Drori Avatar answered Dec 09 '22 15:12

Ori Drori


You can use Array.reduce() for this approach. On each iteration of reduce you can split your string by / and use the first element as a key on the new object and then put the second element on the array associated with that 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;}
like image 41
Shidersz Avatar answered Dec 09 '22 14:12

Shidersz