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

How do i assign key / value pairs of an array of strings

let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']

I’d like to assign key value pairs of the strings i have in the array above

for example:

[{drink: 'soda'},
 {name: 'john'},
 {someKey:'someValue'}
]

I’ve spent hours trying to figure this out… I’ve tried approaching it with the map method but my limited knowledge on javascript is consistently returning errors…

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

I’d really appreciate it if someone could help me out. Thanks

>Solution :

You can do it with a simple for loop:

let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue'];

let result = [];

for(let i = 0; i < arr.length; i+=2) {
  let obj = {}
  obj[arr[i]] = arr[i+1];
  result.push(obj)
}
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