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

1

1 Answer 1

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)

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.