[json] How to loop through a JSON object with typescript (Angular2)

I am new to Angular2 and I am trying to loop through a JSON object that I am getting back from a GET request but can't work it out.

My JSON object:

{
    Results: [{
        Time: "2017-02-11T08:15:01.000+00:00",
        Id: "data-mopdsjkajskda",
        AuthorId: "58fSDNJD"
    }, {
        Time: "2017-03-11T06:23:34.000+00:00",
        Id: "data-2371212hjb1",
        AuthorId: "43555HHHJ"
    }, {
        Time: "2017-04-11T07:05:11.000+00:00",
        Id: "data-kjskdha22112",
        AuthorId: "XDSJKJSDH"
    }]
}

Part of my Angular script:

interface res {
    Time: string;
    Id: string;
    AuthorId: string;
}
export class AppComponent {
    results: res;
    constructor(private _httpservice: HTTPService) {}
    this._httpservice.getQuery().subscribe(
        data => {
            this.results = data.Results
        },
        error => console.log(error),
        () => console.log('Done')
    );
}

I do get the data back - which is great. However, I want to push the Ids into an array. In Javascript I would do this:

var ids = [];

for (i = 0; i < data.Results.length; i++) {
    ids.push(data.Results[i].Id)
}

The array after the push:

ids = ['data-mopdsjkajskda', 'data-2371212hjb1', 'data-kjskdha22112'];

I am struggling to find a way to achieve the same results with Angular2. Any help would be greatly appreciated!

This question is related to json angular typescript

The answer is


Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?


ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

Questions with json tag:

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.? JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to format JSON in notepad++ No String-argument constructor/factory method to deserialize from String value ('') Returning JSON object as response in Spring Boot TypeError: Object of type 'bytes' is not JSON serializable How to send json data in POST request using C# Passing headers with axios POST request How to convert JSON string into List of Java object? npm notice created a lockfile as package-lock.json. You should commit this file RestClientException: Could not extract response. no suitable HttpMessageConverter found Load json from local file with http.get() in angular 2 Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays' How to loop through a JSON object with typescript (Angular2) How to push JSON object in to array using javascript How to check if a key exists in Json Object and get its value REST API - Use the "Accept: application/json" HTTP Header react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined ASP.NET Core return JSON with status code python JSON object must be str, bytes or bytearray, not 'dict Writing JSON object to a JSON file with fs.writeFileSync Convert a JSON Object to Buffer and Buffer to JSON Object back How to parse JSON in Kotlin? How to convert FormData (HTML5 object) to JSON console.log(result) returns [object Object]. How do I get result.name? tsconfig.json: Build:No inputs were found in config file Python - How to convert JSON File to Dataframe How to define Typescript Map of key value pair. where key is a number and value is an array of objects Retrofit 2: Get JSON from Response body Refused to execute script, strict MIME type checking is enabled? Decode JSON with unknown structure How to parse a JSON object to a TypeScript Object Deserialize Java 8 LocalDateTime with JacksonMapper Getting an object array from an Angular service Python - Convert a bytes array into JSON format Passing bash variable to jq Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ What is the difference between json.load() and json.loads() functions Import JSON file in React using setTimeout on promise chain Make XmlHttpRequest POST using JSON

Questions with angular tag:

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7 How to set value to form control in Reactive Forms in Angular Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] WARNING in budgets, maximum exceeded for initial ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found How to set width of mat-table column in angular? How to reload current page? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How to convert string to boolean in typescript Angular 4 Angular: How to download a file from HttpClient? Confirm password validation in Angular 6 Angular 6: saving data to local storage How to use mouseover and mouseout in Angular 6 get current date with 'yyyy-MM-dd' format in Angular 4 Sort Array of object by object field in Angular 6 Setting values of input fields with Angular 6 Select default option value from typescript angular 6 Angular 6: How to set response type as text while making http call Set default option in mat-select How to do a timer in Angular 5 Can not find module “@angular-devkit/build-angular” Could not find module "@angular-devkit/build-angular" How to remove package using Angular CLI? How to add bootstrap in angular 6 project? Can't bind to 'dataSource' since it isn't a known property of 'table' Angular 6 Material mat-select change method removed How to set environment via `ng serve` in Angular 6 Angular 5 Button Submit On Enter Key Press ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]: Set focus on <input> element How to import a new font into a project - Angular 5 Angular - "has no exported member 'Observable'" Uncaught (in promise): Error: StaticInjectorError(AppModule)[options] Property '...' has no initializer and is not definitely assigned in the constructor Angular 5 ngHide ngShow [hidden] not working What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that? Angular - How to apply [ngStyle] conditions How to remove whitespace from a string in typescript? Angular 5 - Copy to clipboard

Questions with typescript tag:

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type? ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead What is "not assignable to parameter of type never" error in typescript? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How to convert string to boolean in typescript Angular 4 What is the Record type in typescript? Angular: How to download a file from HttpClient? Angular 6: saving data to local storage Sort Array of object by object field in Angular 6 How to use `@ts-ignore` for a block Setting values of input fields with Angular 6 Select default option value from typescript angular 6 Angular 6: How to set response type as text while making http call How to do a timer in Angular 5 Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Angular 5 Button Submit On Enter Key Press Importing json file in TypeScript Angular - "has no exported member 'Observable'" Property '...' has no initializer and is not definitely assigned in the constructor How to remove whitespace from a string in typescript? Angular 5 - Copy to clipboard Angular 5, HTML, boolean on checkbox is checked js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check document.getElementById replacement in angular4 / typescript? Exclude property from type How to iterate using ngFor loop Map containing key as string and values as map iteration Read response headers from API response - Angular 5 + TypeScript 'mat-form-field' is not a known element - Angular 5 & Material2 Angular 5 Scroll to top on every Route click Angular File Upload Property 'value' does not exist on type 'Readonly<{}>' No provider for Http StaticInjectorError How to get query parameters from URL in Angular 5? Angular Material: mat-select not selecting default Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf No provider for HttpClient I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular Add items in array angular 4 Angular 4 checkbox change value How to import JSON File into a TypeScript file? How to generate components in a specific folder with Angular CLI?