返回对象的参数

时间:2017-08-01 12:53:20

标签: javascript json angular

我想创建一个函数,当我给我的函数id时,返回一个人的名字。这就是我所做的:

nameOfPerson(personjson, personId){
  let id = personId;
  let json = personjson.json();
  let data = [];

  //console.log("id in nameOfPerson method " + id);
  //console.log("json in nameOfPerson method  " + JSON.stringify(json))

  for (let person of json){
      let newPerson = new Person()
      newPerson.text = person.firstName + ' ' + person.lastName,
      newPerson.id  =  person.id
      if (id == newPerson.id){
        data.push(newPerson.text)
      }
      console.log("data on nameOfPerson method " + JSON.stringify(data))
      return JSON.stringify(data);
  }
}

由此函数调用:

getPersonNamebyId(personId): Promise<Person[]> {
  return this.http.get(this.PersonsUrl)
                      .toPromise()
                      .then(response => this.nameOfPerson(response, personId))
                      .catch(this.handleError)
}

这个叫这个:

//parsingFunction
  parseAppointment(appointmentJson) {
    let data = new Array();
    let json = appointmentJson.json()
      for (let appointment of json) {
        let newAppointment = new Appointment()
        newAppointment.text = appointment.reason +' '+ this.personsService.getPersonNamebyId(appointment.personId), // this.personsService.getPersonNamebyId(appointment.personId)
        newAppointment.id = appointment.id,
        newAppointment.ownerId  =  appointment.personId,
        newAppointment.startDate  =  appointment.date,
        newAppointment.endDate  =  this.add30mnTo(appointment.date),
        data.push(newAppointment);
      }
      console.log(data)
      return data
    }

并在此处致电:

  getAppointments(): Promise<Appointment[]> {

    return this.http.get(this.AppointmentUrlGet)
                 .toPromise()
                 .then(response => this.parseAppointment(response))
                 .catch(this.handleError);

  }

整件事的目标是转换这个对象:

[
{
id: "bc127c74-377b-4ea6-925a-3dd5e0227482",
reason: "testing",
date: "2017-06-22T14:59:55.000Z",
personId: "8090210d-e154-4db0-96c1-42688f45971a"
},
{
id: "bc127c74-377b-4ea6-925a-3dd5e0227482",
reason: "testing02",
date: "2017-06-22T14:59:55.000Z",
personId: "8090210d-e154-4db0-96c1-42688f45971a"
}
]

一个人的对象(id = appointment.id,text = reason + ownerName),这就是为什么我在我的getPersonById函数中使用owner / person.id的原因。

我想将人名附加到personId

在我的控制台日志中,它说[对象对象]不是该人的姓名...... (在约会的单元格上也是一样的)

你能告诉我我的错误在哪里吗?

非常感谢

1 个答案:

答案 0 :(得分:0)

据我所知,你实际上只是想这样做:

var nameOfPerson = (personjson, personId) => {
  var {firstName,lastName,id} = 
    personjson.json().find(el=>el.id === personId);

  return firstName && lastName&&id
    ?  { text: firstName+lastName, id } //maybe Object.assign(new Person(),{text: ... }) instead
    :  { id: "unknown"};
};

像这样使用:

var {text, id} = nameOfPerson(json,12);
console.log(" text",text,"id",id);

或承诺:

 getjson().then(
  json => nameOfPerson(json,12)
 )
 .then(
   ({text, id}) => console.log(text,id)
);