-2

I have string

let str = '1,2,3,4,5,6,7,8,9,0';

I would like to make it as like this.


{
   1:2,
   3:4,
   5:6,
   7:8,
   9:0
}
 

How can I do this ?

Only using map function can not solve this.

james lee
  • 3
  • 2
  • [Step 1](//google.com/search?q=site:stackoverflow.com+js+comma+separated+string+to+array+of+numbers): [How to convert comma separated string into numeric array in javascript](/q/16396124/4642212). [Step 2](//google.com/search?q=site:stackoverflow.com+js+array+key1%2C+value1%2C+key2%2C+value2+to+object): [Chain of \[key1, value1, key2, value2, ...\] to object](/q/63513716/4642212). – Sebastian Simon Nov 30 '22 at 09:41

1 Answers1

0

We can use Array.reduce() to do it

let str = '1,2,3,4,5,6,7,8,9,0';
let result = str.split(',').reduce((a,v,i,arr) => {
  if(i%2 != 0){
     a[arr.at(i-1)] = v
   }
  return a
},{})
console.log(result)
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • So fast reply.. Thanks. Actually what I want is this . { '1':'2', '3':'4', '5':'6', '7':'8', '9':'0' } How can I do this ? a[arr.at(i - 1).toString() ] = v is not working – james lee Nov 30 '22 at 09:45