Beginner
Beginner

Reputation: 9135

creating a object from array of strings

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)

Upvotes: 2

Views: 94

Answers (6)

Nina Scholz
Nina Scholz

Reputation: 386868

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

Upvotes: 5

James Coyle
James Coyle

Reputation: 10428

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)

Upvotes: 3

Atul Sharma
Atul Sharma

Reputation: 10740

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

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122145

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)

Upvotes: 3

R3tep
R3tep

Reputation: 12864

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

Upvotes: 1

binariedMe
binariedMe

Reputation: 4329

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

Upvotes: 2

Related Questions