从响应中仅提取所需的变量 - Angular 7

Extract only required variable from Response - Angular 7

我有如下界面

interface Employee{name?:string;id?:string;role?:string;}

我有这样的回复

{
   "name": "John",
   "id": "ID77777",
   "role": "Engineer",
   "bloodType": "O+ve",
   "placeOfDeployment": "NY"
}

在完成我应该得到的映射后,我只想提取 Interface.So 的成员变量

{
   "name": "John",
   "id": "ID77777",
   "role": "Engineer"
}

您可以使用具有 pick 功能的 lodash 或具有相同结果的普通 js。

const res = {"name": "John","id": "ID77777","role": "Engineer","bloodType": "O+ve","placeOfDeployment": "NY"};

const user = ["name", "id", "role"].reduce((acc, key) => {
  acc[key] = res[key];
  return acc;
}, {})

注意:处理 res 缺少键的情况。

你可以使用对象解构

const response = {
  "name": "John",
  "id": "ID77777",
  "role": "Engineer",
  "bloodType": "O+ve",
  "placeOfDeployment": "NY"
}
// this will extract name,id,role property from response
const {name,id,role} = response;
// create a new object and assign those properties
let obj = {
  name,
  id,
  role
};
console.log(obj)

您可以使用ts-transformer-keys,它使您能够获得给定类型的密钥。

import { keys } from 'ts-transformer-keys';    

const keysOfEmployee = keys<Employee>();
const response = {
  "name": "John",
  "id": "ID77777",
  "role": "Engineer",
  "bloodType": "O+ve",
  "placeOfDeployment": "NY"
};

const result = {};
keysOfEmployee.forEach(k => result[k] = response[k]);