Retrieving Identifiers with Typescript from an object

I'm a newcomer to Typescript and I'm looking to extract ids from an observable

Here's the observable data:

let myObj = [{
  "id": 1,
  "text": "Mary"
}, {
  "id": 2,
  "text": "Nancy"
}, {
  "id": 3,
  "text": "Paul"
}, {
  "id": 4,
  "text": "Cheryl"
}, {
  "id": 5,
  "text": "Frances"
}]

Desired Outcome :

let selectedIds = [1,2,3,4,5];

Is there a way to achieve this without manually creating an array and looping through the data?

Answer №1

Utilize Array#map for mapping one array to another:

const myData = [{"id":1,"name":"John"},{"id":2,"name":"Sarah"},{"id":3,"name":"Ryan"},{"id":4,"name":"Emily"},{"id":5,"name":"Michael"}];

const selectedIds = myData.map(({ id }) => id);

console.log(selectedIds);

Answer №2

<script>
      ..........Your Code for Sending Ajax / JSON Request

      function handleResponse(data)
      {
            var responseArray = JSON.parse(data);

            var chosenIds  = new Array();

            for(var x=0;x < responseArray.length ; x++)
            {
                  chosenIds["[" + responseArray[x].id + "]"] ; 
            }
            document.write(chosenIds);
      }

</script>

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

Efficiently extract objects from an array based on a specific property value and generate a new array with the filtered results

I am dealing with an array that looks like this: Array ( [0] => stdClass Object ( [id] => 227 [catid] => 10 ) [1] => stdClass Object ( [id] => 228 [catid] => 29 ) [2] => stdClass Object ( [id] => 229 [catid] => 11 ) [3] => st ...

Utilize the useTheme type from Emotion Js within ReactJs using Typescript

Greetings! As a newcomer to typescript, I find myself with a query regarding the use of Theme in emotionJs. Here's the snippet of code that has been causing me some trouble: const GlobalStyle: React.FC = (props) => { const Theme = useTheme(); ...

My inquiry was met with silence from the Angular project

I have encountered an issue with my dockerized angular project. Upon starting my container, it appears that the 4200 port is already in use, even though the CMD command within the container does not initiate the application startup. Here is how my Docke ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

Utilize an AJAX call to fetch an array and incorporate it within your JavaScript code

Currently, I am in the process of building a live update chart feature. To access the necessary data, I created a separate file which contains the required information. Through AJAX, I sent a request from my main page to retrieve an Array and incorporate i ...

Google Chart does not show any data when using a PHP array to send information

I am attempting to display an array from PHP code that is returned from my CodeIgniter model/controllers on my page view. Unfortunately, the chart is not being generated, indicating that it might not be receiving the correct data. Here is a snippet of my ...

Karma Test Error: Disconnected due to lack of communication within a 60000 millisecond timeframe

Executing the "ng test" command for Unit Testing in an Angular project is resulting in some errors. Chrome Headless 120.0.6099.130 (Windows 10) ERROR Disconnected , because no message in 60000 ms. Chrome Headless 120.0.6099.130 (Windows 10): Executed 404 ...

PlayWright - Extracting the text from the <dd> element within a <div> container

Here is the structure I am working with: <div class="aClassName"> <dl> <dt>Employee Name</dt> <dd data-testid="employee1">Sam</dd> </dl> </div> I am attempting to retrie ...

Encountering an error with an undefined property while trying to extract information from a JSON string

Here is the JSON string I have: { "data": [ { "id": "533513150124231", "created_time": "2015-02-27T05:23:02+0000", ... }, { "id": "533911933417686", "created_time": "2015-02-28T07:18:09+0000", ... }, { "id": "533471226795090", "created_tim ...

Issue with Nodemon and Typescript causing errors with Worker Threads

Currently, I am in the process of integrating a worker thread into my Typescript and node.js application. Let's take a look at my thread.ts file: import { Worker, isMainThread, parentPort, workerData } from "worker_threads"; let thread ...

retrieving a date from a different source and displaying it in a date

Is there a way to ensure that the date format in an input of type date always follows the dd/MM/yyyy Brazilian pattern, regardless of the computer or browser specifications? <div class="input-group input-group text-center in ...

Rearranging the Array based on the specific number in a consistent manner

I am in the process of developing a quiz creation platform. My goal is to display the answers to a question to users in a randomized order. My aim is to avoid the need to store the sequence in which the answers were presented by shuffling them randomly. ...

Utilize ViewChild to handle changing elements in Angular 2 and Ionic 2 applications

I am facing an issue where I want to dynamically add multiple IonicSlides, but I am unable to use @viewChild. Can anyone suggest a solution for this problem? Template.html : <div *ngFor="let name of title;let i = index;"> <ion-slide ...

Angular 2 Issue: @Input() Directive Not Recognized - Unresolved Reference Error

I am a beginner trying to grasp Angular2 concepts from ng-book 2(v49). Below is the code snippet from article.componenets.ts file: import { Component, OnInit } from '@angular/core'; import { Article } from './article.model'; @Componen ...

Encountering Compilation Issues Post Upgrading to Angular 9

I recently upgraded my Angular application from version 8 to version 9, following the official guide. However, after the upgrade, I encountered errors that prevent my application from building. The specific errors include: "Module not found: Error: Can ...

Implementing the same logic across multiple multidimensional arrays is paramount

Currently, I am experimenting with the following scenario: I have several arrays that are populated by data fetched from a database. While they all have the same columns and data structure, they contain different information. For example, imagine the arra ...

Increase the size of the angular material accordion

I am dealing with a situation where I have 2 different accordion components on the same page. Each accordion contains multiple expansion panels. My challenge is to close all expanded panels from both accordions and only open the currently selected expans ...

"Sequencing http.get requests in Angular 2 using

In my service, I have a series of http.get requests structured as follows: constructor(private http:Http) {} getDetails(sysID:string){ var details; this.http.get('https://blahURL').map(res => res.json().filter(f => f.id == another.id)[0] ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Issue encountered with missing values in array when utilizing the built-in function 'in_array' in PHP alongside mysql_query

I'm still struggling with arrays and it's causing me some frustration. I have a specific issue that I need help with. Currently, I am working on retrieving a data set from a MySQL database using PHP. I receive an array that contains the first ro ...