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 can I turn an array object into an object?

I want to put an array object called hello into a constant called answer. At this time, I want to change the key value of the answer to the value key of hello and the value of the answer to the label value of hello.

how can i do that? i was thinking object entries but i couldn’t do that….
is it possible??

this is my code

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

const hello = [
{ label: 'one', value: 'Tangerinefeed' },
{ label: 'two', value: 'dryexamfeed' },
{ label: 'three', value: 'wetfeed' },
{ label: 'forth', value: 'sawdust' },
{ label: 'five', value: 'etc' },
] ;

expected answer

const answer = {Tangerinefeed: 'one', dryexamfeed: 'two', wetfeed: 'three', sawdust: 'forth', etc: 'five'}

>Solution :

You can use reduce to achieve it

const hello = [
{ label: 'one', value: 'Tangerinefeed' },
{ label: 'two', value: 'dryexamfeed' },
{ label: 'three', value: 'wetfeed' },
{ label: 'forth', value: 'sawdust' },
{ label: 'five', value: 'etc' },
] ;

const finalResult = hello.reduce((result, item) => {
  result[item.value] = item.label
  return result
}, {})

console.log(finalResult)
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