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

Create a dynamic number of object keys with "true" values in Javascript

I want to create an object with every value as "true" and the length of keys will be same with array length.

Example :

const myCar = [{name:ford,type:A},{name:opel,type:B}] 

The output want to be like this below

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

{0:true,1:true}

If the length from the array myCar will be 3 so the output will be like this as well:

{0:true,1:true,2:true}

>Solution :

You can reduce to get a counter and an object

const myCar = [{ name: 'ford', type: 'A' }, { name: 'opel', type: 'B' }];

const myObj = myCar.reduce((acc,_,i) => (acc[i] = true,acc),{});

console.log(myObj);

Breakdown

const myObj = myCar
  .reduce(
    (acc,_,i) => // reduce passes the accumulator, the current object which we ignore here and the index
      (acc[i] = true // set the accumulator at key=index to true 
         ,acc)   // and use the comma operator to return the accumulator
     ,{});       // initialise the accumulator to an empty object
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