Ways to extract information from an Object and save it into an array

In my Angular2 project, I am working on retrieving JSON data to get all the rooms and store them in an array.

Below is the code for the RoomlistService that helps me fetch the correct 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());
  }
}

Here is the Component that utilizes the service to retrieve the data:

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

As of now, everything is functioning correctly, and when using console.log, I can see the object being returned.

https://i.sstatic.net/WYii8.png

My goal is to extract all rName values from the object and store them in an array. However, my attempts have been unsuccessful so far. Any assistance in achieving this would be greatly appreciated.

Answer №1

The image in your question doesn't provide a clear view of the structure of the data object, but based on what I can see, this code should do the job:

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

Answer №2

Another sleek method is to utilize ".map".

 const roomNames = data.map(room => {return room.name})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The art of properly parsing JSON in AngularJS

Still a newbie in AngularJS, but I am determined to learn. Currently, I have the following controller set up. It retrieves JSON data from a specified URL. app.controller('PortfolioItemCtrl', ['$scope', '$routeParams', &apos ...

Error in ReactJS: TypeError - Trying to convert undefined or null as an object

Here is the affected code with Typescript errors in local. The component name is correct: {template.elements.map((element: TemplateElementModel, i) => { const stand = roomStands?.find( (stand: ExhibitorModel) => stand.standN ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

Struggling with retrieving the $id variable from the view in both the controller and the database through Ajax

While checking my view, I noticed that the variable $id is visible. However, when I send it through Ajax, it ends up as NULL in the database. The way I'm sending the variable $id from the view using Ajax is like this: $.ajax({ url:'{ ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

Transform a JSON object into a flat structure by creating key-value pairs

I received a JSON object in the following format: { "id": "1", "name": "Hw", "price": { "value": "10" }, { "items": [{ "id": "1" }] } } My goal is to convert this into a flat map, but with the a ...

When using Selenium WebDriver to locate an object, an error may occur stating that the result of the xpath expression is "[object Text]" instead of an element as expected

I am currently utilizing Selenium to validate the existence of specific text within a web page. Here is an example of how the HTML appears. <html> <div class="a-content"> <!--!-->==$0 " Text to Locate" <b ...

Laravel Model that handles JSON data

Is it possible to write a model in Laravel that does not rely on a database, and includes a function getData that returns JSON? It should resemble the following code: <?php namespace App; use Illuminate\Database\Eloquent\Model; cla ...

Exploring subobjects while fetching observables (typescript/angular)

When retrieving JSON from an API into an Angular service, I am working with a collection of objects structured like this: { "data": { "id": 1, "title": "one" }, "stats" : { "voteCount": 8 } } I am particularly interested in the ' ...

Creating HighStock charts on the server-side using NodeJS

I'm currently utilizing HighStock to create charts within the browser. However, I now have a need to save some of these charts on the server. While I understand that HighCharts offers an export option to the server, I am interested in exploring other ...

Using Typescript to Convert JSON Data into Object Instances

My challenge involves a Json object structure that looks something like this: { "key" : "false", "key2" : "1.00", "key3" : "value" } I am seeking to convert this in Typescript to achieve th ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

Webpack has made Rails .js.erb templates obsolete

Recently, I migrated my Rails application to use WebPack for handling assets, and it has been operating smoothly. However, I encountered an issue with JS templates located in my views directory (*.js.erb) that require jQuery. Since jQuery is included in my ...

When I test my jQuery scripts in jsfiddle, they run smoothly. However, they do not seem to work properly when I

My code is almost perfect, but the jQuery function is giving me trouble. It works fine in jsfiddle, but for some reason, it's not functioning in my HTML file. I don't believe extra characters are being added when copying from the HTML file. I hav ...

Ensure that Google Tag Manager (GTM) delays the pageview until the SPA URL title is available

I'm dealing with a React SPA that manages all the URL titles on the frontend, so the historyChange event registered on GTM captures the visited URLs along with their titles correctly. However, I've noticed that on the initial load of the SPA, su ...

What is the best way to use a computed property as a style value for a component in Vue.js?

My component's template includes the following HTML element: .grid-item(:style="{ width: columnWidth, backgroundColor: 'blue' }") I want to dynamically set the width of this element using a computed property: computed: { columnWidth () ...

Unlock the secret to retrieving specific properties from a JSON object

Whenever this code is executed: import requests import json def obtain_sole_fact(): catFact = requests.get("https://catfact.ninja/fact?max_length=140") json_data = json.loads(catFact.text) return json_data['fact'] print(obtain_s ...

I hope to retrieve a specific string from an array using PHP

Recently, I installed a WordPress plugin that allows me to rearrange posts easily. This particular plugin showcases the post_name within a drag-and-drop box. Now, what I want to achieve is changing the format of the "post_name" to "post_name - custom f ...

ngModelChange doesn't trigger if the value is manually altered

Here is the scenario I am experiencing: //html <input (ngModelChange)="onSelection()" [(ngModel)]="selectedNode" > // in the ts file onSelection() { alert('changed'); } Typing something inside the input tri ...