A guide to accessing a property value in Angular 6 from an object using a string key

In my Angular application, I am receiving an object with multiple arrays from a REST service.

I need to access the value from the incoming object based on the property name.

Here is what the object looks like:

data{
array1:{},
array2:{},
array3:{}
}

The number of arrays and their names can vary. I have another array containing all these array names like...

arraynames = {array1,array2,array3}

I have attempted to retrieve the value using...

data[arraynames[0]]
or
data[0]
or 
data[array1]

However, none of these methods seem to be working as they are returning undefined.

Is there a way for me to successfully retrieve the value of an array from data?

Answer №1

One way to access the data is by using:

Object.values(info)[0];
//or
info.array1

Answer №2

For your array to function correctly, it must be a string array in the following format: arrayNames = ['array1', 'array2', 'array3']. This way, you can access the data using data[arrayNames[0]].

Answer №3

Give it a shot:

class MainComponent {
  list = {
    item1: {id:1},
    item2: {id:2},
    item3: {id:3}
  }

  items = ["item1", "item2", "item3"]

  constructor() {
    this.items.forEach(element => {
      console.log(this.list[element])
    });
  }
}

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 impact of Ajax on jQuery document loading within an Ajax form

I'm currently using jQuery to change the colors of cancelled bookings in a Drupal view, and it's working well. jQuery(document).ready(function(){ jQuery(".bookingstatus:contains('Cancelled')").css("color","red"); }); However, when ...

Tips for customizing your MUI slider design

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

modifying variable values does not impact what is displayed on the screen

I'm currently facing an issue with AngularJS. I have two HTML blocks within an ng-repeat and I need to display one of them at each step. <div class="col-md-3" style="margin-top:80px" ng-init="checkFunction()"> <div id="left_group_stage"& ...

Retrieving template variable within a directive's host listener function

Can 'habitCellInfo' be accessed from the template within the onvalueChanged host listener? <div *dxTemplate="let habitCellInfo of 'habitEditCellTemplate'"> <dx-select-box (onValueChanged)=" onHabitEdi ...

Raycast in Three.js is struggling to locate object

Whenever I select a 3D model, my goal is to retrieve the object's ID, name, or the actual object itself in order to effectively delete it. function onDocumentMouseDown( event ) { if (enableRaycasting){ event.preventDefault(); mouse.set( ( event.c ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

Displaying array elements on a webpage using JavaScript in HTML

Looking to display multiple blocks in HTML using a JavaScript array. The array contains names such as: var name=['amit','mayank','jatin'];. I need to repeat a certain portion of code in order to show the elements of the array, ...

Once the "Get Route" button is pressed, I want to save my JavaScript variable into a database

I am seeking to automatically extract data from the Google Maps API and store it in my MySQL database. Specifically, I want details such as source address, destination address, distance, and duration for all available routes to be inserted into my database ...

Utilizing ng-class to manipulate arrays in AngularJS

Within my controller's $scope, there is an array called myElements... $scope.myElements = [false, false, true, false, true, false]; ...and I want to assign the class firstClass to a div element if any of the elements in the array are true, otherwise ...

Redis Recursion: The callstack has reached its maximum size limit

Looking for some assistance with creating a game timer. I've decided to utilize Redis and Web Sockets in order to synchronize the timer across multiple devices. However, I'm running into an issue when trying to call my function recursively using ...

Step-by-step guide on populating input fields with JSON data for each row

As a beginner in Programming, I have been searching for an answer to the following problem on this site for days but haven't been able to figure it out yet. To explain briefly, there will be an input form where the user can define the number of rows ...

Troubleshooting the issue with the htmlFor attribute

I have encountered an issue with creating radio buttons and labels using JavaScript. Despite adding the 'for' attribute in the label using 'htmlFor', it does not apply to the actual DOM Element. This results in the label not selecting t ...

Ensuring various conditions with ngIf

I've created a toggle function that updates the text of a link, but I'm struggling to handle multiple conditions. For example, *ngIf="condition1 or condition2". Below is an excerpt from my code: <a routerLink="/ads" class="tip" (click)="togg ...

Executing Passport.js for Authentication

I've been trying to understand passport.js by watching tutorials online, but I'm still confused. Can someone clarify my doubts below? Please read the paragraph at the bottom first. If everything is set up correctly, this is how the login strateg ...

What is causing the button within my ExtJS grid to display as "[object Object]"?

Within an ExtJS grid, I am facing a scenario where I need to display a button in a specific column when the content of a cell meets certain criteria. To achieve this, I define the column with the button using a rendering function as shown below: { he ...

Send the form data from a modal controller in AngularJS to an ng-controller outside of the modal

There seems to be a confusion with the functionality not working as expected: In my Angular application, I have a main page with an ng-controller named "SearchCtrl" that handles sending search requests to a webserver. app.controller('SearchCtrl&apos ...

Assigning the output of a function to an Angular2 component (written in TypeScript)

I have a small utility that receives notifications from a web socket. Whenever the fillThemSomehow() method is called, it fetches and stores them in an array. @Injectable() export class WebsocketNotificationHandler { notifications: Array<Notificati ...

Eliminate spaces within a string using JavaScript

In my quest for knowledge about trimming strings in JavaScript, I came across this intriguing discussion with a regex-based solution. After learning from the thread, I was under the assumption that trim would eliminate the space between "Hello" and "World ...

SvelteKit is having trouble with identifying Typescript syntax

I was working on a SvelteKit project with TypeScript (set up with Vite) and everything was running smoothly with "npm run dev". However, when I attempted to publish the app on Github Pages, an error popped up (on localhost) as I hovered over the only link ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...