How to map Object with 4 properties to Object with 3 properties?

Advertisements

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:

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

Leave a ReplyCancel reply