从字符串数组创建对象

时间:2019-03-06 13:20:13

标签: javascript

我的输入就像

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)

6 个答案:

答案 0 :(得分:5)

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

def search_requests
requests = Request.all

requests = requests.where("created_at > ? AND completed_at < ?", date_from, date_to)
requests = requests.where(["title LIKE ? OR description LIKE ?", "%#{keywords}%", "%#{keywords}%"]) if keywords.present?
requests = requests.where(["incomplete LIKE ?", incomplete]) if incomplete.present?

return requests
end

答案 1 :(得分:3)

您可以在此处将reduce方法与对象一起用作累加器值。

var data = ["user-john", "user-doe", "students-Milan"];
var result = data.reduce((r, e) => {
  let [key, value] = e.split('-');
  r[key] = (r[key] || []).concat(value)
  return r;
}, {})

console.log(result)

答案 2 :(得分:3)

干净,现代的解决方案:

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

const output = {}

resources.forEach(item => {
  const [key, value] = item.split('-')      
  output[key] = [...output[key] || [], value]
})

console.log(output)

答案 3 :(得分:2)

var resources = ["user-john","user-doe", "students-Milan"];
var tmp = {};
resources.forEach(function(e){
	var a = e.split("-");
	if(typeof tmp[a[0]] == "undefined"){
		tmp[a[0]] = [];
		tmp[a[0]].push(a[1]);
	}else{
		tmp[a[0]].push(a[1]);
	}
});
console.log(tmp);

答案 4 :(得分:1)

在此部分,您实际上需要:

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

答案 5 :(得分:1)

您可以使用.push方法代替[...tempArr[1], tempArr[1]]

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

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

console.log(tempObj)

或者您可以在数组的最后一个状态(如[...tempObj[tempArr[0]], tempArr[1]]而不是[...tempArr[1], tempArr[1]]

上使用扩展语法)