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

Simple array to objects with changing key

I got a comma seperated list

var arr = [1,2,3,4]

and want it to be:

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

var new_arr = [
 {x:1, y:2},
 {x:3, y:4}
]

Struggeling how to get the key/value change done.

>Solution :

You could use Array.reduce() to return the desired result.

If the element index is even, add a new item to the result, if not skip it.

const input = [1,2,3,4]
 
const result = input.reduce((acc, el, idx, arr) => { 
    return (idx % 2) ? acc : [...acc,  { x: el, y: arr[idx + 1]} ];
}, []);
 
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }
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