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 to change index to value in an Object

const arr= [
{
"name":"Toyota"},
{"name":"Renault"},
{"name":"Jeep"},
]
  
  const array_unique = (arr) => Array.from(new Set(arr));
  
  const car = array_unique(
    array.map((item) => item.name),
  ).sort();// ['Toyota', 'Renault', 'Jeep']

  const car_map = Object.fromEntries(
    car.map((car,index) => [car,index]),
  );//{Toyota: 0, Renault: 1, Jeep: 2,}

Is there any possibility to change the index like 0, 1, 2 into car name
like:

{Toyota: Toyota, Renault: Renault, Jeep: Jeep,}

>Solution :

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

You can use map() and Object.fromEntries() methods

const arr = [
  { name: "Toyota" },
  { name: "Renault" },
  { name: "Jeep" },
];

const array_unique = (arr) => Array.from(new Set(arr));

const carNames = array_unique(arr.map((item) => item.name)).sort();

const carMap = Object.fromEntries(carNames.map((name) => [name, name]));

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