You have to process the recieved response in your required format.
findAllPersons(): Observable<Person[]> {
return this.httpClient.get<object>('url');
}
findAllPersons().subscribe((response) =>{
let array = [];
for(let key in response){
let p = new Person();
p.firstName = key;
p.lastName = response[key];
array.push(p);
}
console.log(array); // your required array
});
Answer from khush on Stack OverflowYou have to process the recieved response in your required format.
findAllPersons(): Observable<Person[]> {
return this.httpClient.get<object>('url');
}
findAllPersons().subscribe((response) =>{
let array = [];
for(let key in response){
let p = new Person();
p.firstName = key;
p.lastName = response[key];
array.push(p);
}
console.log(array); // your required array
});
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
interface NameData {
[firstName: string]: string;
}
interface Person {
firstName: string;
lastName: string;
}
@Injectable()
class PersonService {
constructor(private httpClient: HttpClient) {}
findAllPersons(): Observable<Person[]> {
return this.httpClient.get<NameData>('url').pipe(
map((v) =>
Object.entries(v).map(([firstName, lastName]) => ({
firstName,
lastName,
}))
)
);
}
}
I am reading in a JSON file and attempting to convert them to an array of objects. I get a syntax error on the component file.
This is the component code:
import * as blogs from '../story/stories.json';
import { IStory } from '../models/story';
@Component({
selector: 'app-story',
templateUrl: './story.component.html',
styleUrls: ['./story.component.scss']
})
export class StoryComponent implements OnInit {
stories: IStory[] ;
constructor() { }
ngOnInit() {
this.stories = blogs; <-- syntax error on this line
}this is the story.ts file:
export interface IStory {
id: number;
author: string;
title: string;
pictureUrl: string;
body: string;
}This is the json file, stories.json
[
{"date":3,"author":"AVC", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"},
{"date":4,"author":"ADF", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"}
]The interface has an iD field and the json has a date field. They need to be the same types. You also might need to use JSON.parse(stringValue) depending on how you are getting the JSON data.
It might be simpler to just use the http client to get the json. Pass it the type and you should get proper data objects back.
Convert JSON objects to JSOn array
angularjs - Convert json object in to array to iterate through ng-repeat using Javascript? - Stack Overflow
angular - Angular2: converting object to an array for json file - Stack Overflow
How to convert array to json format objects using AngularJS
Use Object.keys and pass them on to Array.prototype.map to create the array that you want - see demo below:
var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};
var result = Object.keys(object).map(e=>object[e]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
EDIT:
Correcting the solution to make list1 an array:
var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};
var result = Object.keys(object).map(function(e){
Object.keys(object[e]).forEach(function(k){
if(typeof object[e][k] == "object") {
object[e][k] = Object.keys(object[e][k]).map(function(l){
return object[e][k][l];
});
}
});
return object[e];
});
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
You can recursion but do note this can cause freeze for big objects and can also lead to Maximum Call Stack exceeded
Logic
- Loop over object and check if all entries are objects.
- If yes, then a simple
Object.keys(obj).map(x=>obj[x])will do. - If not, then you will have to copy individual values and if object, then again loop in it for inner objects. A simple way is to loop on every key and if type is not object, just return value.
function ObjectToArray(obj) {
if (typeof(obj) === 'object') {
var keys = Object.keys(obj);
var allObjects = keys.every(x => typeof(obj[x]) === 'object');
if (allObjects) {
return keys.map(x => ObjectToArray(obj[x]));
} else {
var o = {};
keys.forEach(x => {
o[x] = ObjectToArray(obj[x])
});
return o;
}
} else {
return obj;
}
}
var d={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};
console.log(ObjectToArray(d))
Use map(t=> t.json()):
return this.http.get(this.heroesUrl)
.map (t=>t.json())
.toPromise()
...
Your problem is that you were trying to loop and access the array before parsing the JSON in :
heroes[i] = JSON.parse(response.text()[i]);
//And then in
heroes[i] = JSON.parse(response.text()[i]);
You should parse the JSON before accessing the array an looping over its elements:
let jo = JSON.parse(response.text());
console.log("jo: "+jo);
for(let i=0;i<jo.length;i++){
console.log("ele: "+jo[i]);
heroes[i] = jo[i];
}
This is just a hint/suggestion, something you might overlooked. It is hard to understand your question, clarify if this is not what you are looking for.
Maybe for some reason you got "{"y":"1","a":"0"}" back, which is a string.
If you need to get a JSON object from it then use JSON.parse(string) function.
Use this method is used to convert json string response to an array, object, number
var temp = [];
temp = angular.fromJson(json);
console.log(temp);
This function will convert and return
https://docs.angularjs.org/api/ng/function/angular.fromJson
If you just want to convert it to Array, you can use JSON.parse()
var result = [];
var in1 = '{"testSuiteID" : 1, "testSuiteName" : "Dummy Name", "timestamp":"1jan2017_8_00_pm", "testsuite_JSONfile" : "IamNewlyGeneratedJSON.json"},{"testSuiteID" : 2, "testSuiteName" : "Dummy Name2", "timestamp":"1jan2017_820_pm", "testsuite_JSONfile" : "IamNewlyGeneratedJSON_2.json"}';
result=JSON.parse("["+in1+"]");
console.log(result);
It's a little weird what you're trying to do, but ideally the endpoint should be returning a proper JSON array in your situation.
If you're trying to wrap it around square brackets it's just simple string manipulation.
var json = "{}"
function wrapInBrackets(myStr) {
return '[' + myStr + ']'
}
To convert it to a proper json object, you need to use JSON.parse()
var obj = JSON.parse(wrapInBrackets(json));
It should be:
http.get('', { headers: ''})
.map(response => {
return response.json().map(d => {
return new class(d.url);
});
});
if using lodash then ..
var urls = _.map(yourArray, 'url');
or ES6 and lodash ..
let urls = _.map(yourArray, 'url');
or ES6 and no lodash ..
lets urls = yourArray.map((obj) => {
return obj.url;
});
or ES5 and no lodash ..
lets urls = yourArray.map(function (obj) {
return obj.url;
});
To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
That's correct, your response is an object with fields:
{
"page": 1,
"results": [ ... ]
}
So you in fact want to iterate the results field only:
this.data = res.json()['results'];
... or even easier:
this.data = res.json().results;
you can use class-transformer which helps you to convert plain javascript objects to real es6 classes. With this real instances you can also use class methods.
import { Component, OnInit } from "@angular/core";
import ProductsJson from "./products.json";
import {plainToClass} from "class-transformer";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
productsJson: any = ProductsJson;
products: Array<Product>;
constructor() {}
ngOnInit() {
//this.products = <Product[]>this.productsJson;
this.products = plainToClass(Product, this.productsJson as []);
console.log(this.products);
}
}
export class Product {
id: number;
name: string;
description: string;
relatedProducts: Array<number>;
getId(){
return this.id + "_ID";
}
}
template:
<ul>
<li *ngFor="let p of products">
{{p.getId()}} {{p.id}} {{p.name}}
</li>
</ul>
look at stackblitz
Let me know still you have an issue..
thanks