0

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.

1
  • You're making an array of new objects with keys made from the values of one property and values from another. The title sounds like you just want Object.keys(arr). Commented Oct 8, 2021 at 12:20

1 Answer 1

4

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.