我帮助您翻译内容,这是关于IT技术的问题。
我正在尝试从一个字符串数组创建一个对象。
我有这个字符串数组:
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;
}
}
我相信有更好的解决方案,但是我自己无法做到。
所以我很愿意接受任何帮助!
提前感谢!
origin/abc/def
这样的格式,那么它只会取abc
,而不是abc
和def
。 - brk