javascript - Create an object from a string array - Stack Overflow

I'm trying to create an object from a string array.I've this string array :let BaseArray = [&

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 !

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 !

Share Improve this question asked Mar 8, 2019 at 19:15 NuljiNulji 4573 silver badges9 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 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);

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

You can use split and reduce

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)

You can use the reduce method to build your object.

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

You can use reduce & split the string which will give an array. Then use the element at index 0 of the array to create the object key. And push rest of the value to the array

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)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745127042a4612750.html

相关推荐

  • javascript - Create an object from a string array - Stack Overflow

    I'm trying to create an object from a string array.I've this string array :let BaseArray = [&

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信