基于其他对象属性返回转换对象

时间:2018-01-12 03:42:41

标签: javascript function typescript

有没有办法根据某些属性值从JavaScript函数返回一个对象?

例如:

let personDetails = {
    name: 'Bob',
    age: 25,
    occupation: 'Software Engineer',
    hobby: 'Not Programming on a Thursday night',
    pets: ['Dog', 'Cat']
};

想象一下Person模型:

export interface Person {
    name: string;
    age: number:
}

另外,PersonDetails模型:

export interface PersonDetails {
    name: string,
    age: number,
    occupation: string,
    hobby: 'string',
    pets: string[]
}

然后最后,做以下事情:

public persons: Person[];
public personDetails: PersonDetails[];

let person = this.personDetails.map(this.toPersonModel.bind(this));

toPersonModel(personDetails: PersonDetails[]): Person {
    // If a person has more than 2 pets, return a simplified model
    // Can we do something like a filter here?
    if (personDetails.pets.length > 2) {
        return {
            name: personDetails.name,
            age: personDetails.age
        };
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用reduce实现此目的。

export interface PersonDetails {
    name: string,
    age: number,
    occupation: string,
    hobby: string,
    pets: string[]
}
export interface Person {
    name: string;
    age: number;
}
var reducer = function(persons:Person[], personDetails:PersonDetails):Person[] {
    if (personDetails.pets.length > 0) {
        let person: Person = {
            name: personDetails.name,
            age: personDetails.age,
        }
        persons.push(person);
    }
    return persons;
}
let personDetails: PersonDetails[] = [
    {
        name: 'Alice',
        age: 29,
        occupation: 'Analyst',
        hobby: 'Ham radio',
        pets: ['Cat']
    },
    {
        name: 'Bob',
        age: 25,
        occupation: 'Software Engineer',
        hobby: 'Not Programming on a Thursday night',
        pets: ['Dog', 'Cat']
    },
];
var persons = personDetails.reduce(reducer,[]);

答案 1 :(得分:0)

要记住的一件事是你有继承权。所以你可以构建实际的基类型。

export interface Person {
    name: string;
    age: number;
}

export interface PersonDetails extends Person {
    occupation: string;
    hobby: 'string';
    pets: string[];
}

但是因为这些是接口,他们只说这个对象必须至少具有这些属性,并且感觉我们的Details对象是一个人无用(铸造赢得了删除额外的属性)以尝试将其返回为一个人。

我建议改用类。

export class Person {
  name: string;
  age: number;

  constructor(args: Partial<Person>) {
    Object.assign(this, args);
  }
}

export class Details extends Person {
  pets: any[];

  constructor(args: Partial<Details>) {
    super(args);
  }
}

export function PetCheck(p: Details): Person {
  if (p.pets.length > 2) {
    return new Person(p);
  }

  return new Details(p);
}