2

My input is like

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

I am trying to get an output as an object like below,

{
  user: ["john", "doe"],
  students: ["Milan"]
}

What am i doing wrong

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 Answers 6

5

You could deconstructure the splitted string and build an array as value.

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

Sign up to request clarification or add additional context in comments.

Comments

3

You could use reduce method here with an object as a accumulator value.

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)

Comments

3

A clean, modern solution:

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)

Comments

2

Here in this part you actually need to :

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

Comments

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

Comments

1

You can use .push method instead [...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)

Or you can use the spread syntax on the last state of your array like [...tempObj[tempArr[0]], tempArr[1]] instead [...tempArr[1], tempArr[1]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.