Nonsense
Nonsense

Reputation: 290

How to get an object from an array?

I have an array in which there are a number of records and I want to get from this array only one record by id in the form of an object. But as a result, I get an array from one record.

How can this be fixed?

Result:

[{…}]
   0: {id: 1, fname: "Tommie", lname: "Shurtleff", photo: "tommie", money: 667.16}
   length: 1
   __proto__: Array(0)

ts:

  user: User;
  load() {
    this.route.params
      .pipe(
        switchMap(
          (params: Params) => {
            if (params['id']) {
              return this._peopleService.getPeopleById(params['id'])
            }
            return of(null)
          }
        )
      )
      .subscribe(
        (user: User) => {
          this.user = user;
          console.log(this.user)
        },
        error => {
          console.log(error)
        }
      )
  }

service:

getPeopleById(id: number): Observable<User> {
    return this.http.get<User>(`http://localhost:7000/users?id=${id}`);
}

json:

{
    "users": [
        {
            "id": 1,
            "fname": "Tommie",
            "lname": "Shurtleff",
            "photo": "tommie",
            "money": 667.16
        },
        ...
    ],
    ...
}

Upvotes: 0

Views: 53

Answers (2)

Benjamin
Benjamin

Reputation: 1

Just map it to single object on the service level. As far as you only getting particular user for provided 'id', it should be fine.

getPeopleById(id: number): Observable<User> {
    return this.http.get<User>(`http://localhost:7000/users?id=${id}`)
            .pipe(map(users => users[0]));

}

Upvotes: 0

Wai Yan Moung
Wai Yan Moung

Reputation: 269

How to get an object from an array? This is the answer

var yourvariable = array[index]["fieldname"]; you can use like that in every programming language like that

Upvotes: 1

Related Questions