Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript how to make json from string?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Only using map function can not solve this.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading