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 map Object with 4 properties to Object with 3 properties?

I have two Object

one is role:

Role {
    roleId: string;
    name: string;
    description: string;
    isModerator: string;
}

role = {
    roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1",
    name:"HR",
    description:"HR of the Company",
    isModerator:"N"
}

and 2nd is roleDetails:

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

RoleDetails {
    name: string;
    description: string;
    isModerator: string;
}

I want to assign roleDetails = role;
so when I console.log(roleDetails)
I should get:

roleDetails = {
    name:"HR"
    description:"HR of the Company"
    isModerator:"N"
}

>Solution :

You can simply assign each property individually (also note I’ve added , in your original object between each value):

let role = {
  roleId: "8e8be141-130d-4e5c-82d2-0a642d4b73e1",
  name: "HR",
  description: "HR of the Company",
  isModerator: "N"
};

let roleDetails = {
  name: role.name,
  description: role.description,
  isModerator: role.isModerator
};

console.log(roleDetails);

You could also do this dynamically with an array of keys:

let role = {
  roleId: "8e8be141-130d-4e5c-82d2-0a642d4b73e1",
  name: "HR",
  description: "HR of the Company",
  isModerator: "N"
};

let keys = ["name", "description", "isModerator"];

let roleDetails = Object.entries(role).reduce((a, [k, v]) => {
  if (keys.includes(k)) a[k] = v;
  return a;
}, {});

console.log(roleDetails);

And also with an array of keys to exclude:

let role = {
  roleId: "8e8be141-130d-4e5c-82d2-0a642d4b73e1",
  name: "HR",
  description: "HR of the Company",
  isModerator: "N"
};

let keysToExclude = ["roleId"];

let roleDetails = Object.entries(role).reduce((a, [k, v]) => {
  if (!keysToExclude.includes(k)) a[k] = v;
  return a;
}, {});

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