Home > Mobile >  create a new array from the keys of an Array's Object
create a new array from the keys of an Array's Object

Time:10-12

I have a array of objects, and by using the foreach or map I want to create new array from its keys:

[{
    "name": "Dentist Specialist",
    "category": "Roles",
    "path": "cde"
},
{
    "name": "Root Canal Therapy",
    "category": "Procedures",
    "path": "abc"
},
{
    "name": "Live Course",
    "category": "Course Type",
    "path": "mfg"
}]

From the above array I need a new ARRAY which will look like this:

[{
    "Roles": "Dentist Specialist"
},
{
    "Procedures": "Root Canal Therapy"
},
{
    "Course Type": "Live Course"
}]

Just replace the 2nd key with the first key and remove the rest.

CodePudding user response:

You can use map here to achieve the desired result.

arr.map(({ category, name }) => ({ [category]: name }));

or

arr.map((o) => ({ [o.category]: o.name }));

const arr = [
  {
    name: "Dentist Specialist",
    category: "Roles",
    path: "cde",
  },
  {
    name: "Root Canal Therapy",
    category: "Procedures",
    path: "abc",
  },
  {
    name: "Live Course",
    category: "Course Type",
    path: "mfg",
  },
];

const result = arr.map((o) => ({ [o.category]: o.name }));
console.log(result);

  • Related