我的输入就像

var resources = ["user-john","user-doe", "students-Milan"];

我正在尝试获得如下所示的对象输出,
{
  user: ["john", "doe"],
  students: ["Milan"]
}

我究竟做错了什么

var resources = ["user-john","user-doe", "students-Milan"];

let tempObj = {}
resources.forEach(o => {
 let tempArr = o.split("-");
   if(tempObj[tempArr[0]]){
     tempObj[tempArr[0]] = [...tempArr[1], tempArr[1]]
   }else{
     tempObj[tempArr[0]] = [tempArr[1]]
  }
})

console.log(tempObj)

最佳答案

您可以解构拆分后的字符串并构建一个数组作为值。

var resources = ["user-john", "user-doe", "students-Milan"],
    result = resources.reduce(
        (r, s) =>
            ((key, value) => Object.assign(r, { [key]: [].concat(r[key] || [], value) }))
            (...s.split('-')),
        {}
    );

console.log(result);

09-16 20:26