Anna F
Anna F

Reputation: 1683

How retrieve data from Object and store it to an array

I write project in Angular2, where I want to get JSON and retrieve all rooms in an array.

Here is my Service, which helps me to get right json-file

@Injectable()
export class RoomlistService {

  constructor(private http: Http) { }
  getRooms(room) {
    console.log('get all rooms: ');
    return this.http.get('../../assets/rooms/' + room + '.json')
      .map(response => response.json());
  }
}

And here is my Component, which uses this service and get data

  ngOnInit() {
    this.routeUrl.paramMap.subscribe( (param) => {
      this.buildingID = param.get('id');
      this.service.getRooms(this.buildingID).subscribe(data => {
        console.log(data);
      });
    });
  }

So, for now it works fine, and with console.log I get this object

enter image description here

What I would like to do is to get all rName and store it to an array. But everything I tried did not help me. Could you please help me to solve it?

Upvotes: 0

Views: 57

Answers (2)

NicoLA
NicoLA

Reputation: 71

you can also use ".map" in a cleaner way.

 let roomArray = data.map(roomObject => {return roomObject.rName})

Upvotes: 1

Titus
Titus

Reputation: 22474

Is not clear what the structure of the data object is really like from the image in your questing but I think this will work:

var arr = Object.keys(data).map(k => data[k].rName);

Upvotes: 1

Related Questions