Reading JSON into arrays in Angular (HttpClient) - arrays

i am trying to read JSON into different arrays using HttpClient for the use in Echarts, but since i am a newbie i couldn't find how to fill JSON into the different arrays.
the part code i used so far was:
....
label: Array<any>;
data: Array<any>;
tooltip: Array<any>;
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
this.data=data.data;
this.label=data.label;
this.tooltip=data.tooltip;
console.log(data)
});
}
public getJSON(): Observable<any> {
return this.http.get("./assets/JSONData/TeamProgress.json")
}
the JSON file is formatted like this:
[{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
...etc
i want to be able to get all labels of JSON in one array, and all data in another array, and all tooltips in a third array.
it would be great if you can help me.
thanks

First the result of that file should be a valid JSON structure aka (an object with key-values) you can group the array under a key called per example result
{
"result": [
{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
//....Etc
]
}
Then you can access the data and filter it using map as below:
this.getJSON().subscribe((data:any) => {
this.label = data.result.map(element =>
// if you want to return an array of objects
{return {"label": element.label}}
// or if you want to return the raw values in an array, just do
element.label
});
this.data = data.result.map(element => {
return {"data": element.data}
});
this.tooltip = data.result.map(element => {
return {"tooltip": element.tooltip}
})
})

Related

How to push array value with defined object in angular

My array
let myArr=["test1","test2"];
Need to add the object like below
let myFinalArr=[["test1":{"val1":"XXX","val2":"YYY"}],["test2":{"val1":"XXX","val2":"YYY"}]];
how to push the data like above in angular.
There are multiple ways to do it. How exactly does the requirement look? Does the object remain same for all the elements in the array?
And expanding from your comment that the following is the actual output's structure
{
"test1": { "val1":"XXX", "val2":"YYY" },
"test2": { "val1":"XXX", "val2":"YYY" }
}
You could try the Array#reduce with spread operator to transform the array
let myArr = ["test1", "test2"];
const output = myArr.reduce((acc, curr) => ({
...acc,
[curr]: { val1: "XXX", val2: "YYY" }
}), Object.create(null));
console.log(output);

How to extract array from json on Angular

I'm working with angular2 ( version 5).
I make an http request an get back json.
I know how to access and use value but not the array.
and I don't find how to extract the two array inside element.
here my json:
{ "ImpiantiProva": [
{
"nomeImpianto":"MFL1",
"descrImpianto":"Multifilo 1",
"posizione":"Place1",
"dati_status": "true",
"unita_misura": "m/s",
"vel_attuale": 11.5,
"vel": [24.5,13.6,34.6,12.1],
"orario": ["17.05","17.06","17.07","17.08"]
},
{
"nomeImpianto":"MFL2",
"descrImpianto":"Multifilo 2",
"posizione":"Place2",
"dati_status": "true",
"unita_misura": "m/s",
"vel_attuale": 12.5,
"vel": [24.5,13.6,34.6,12.1],
"orario": ["17.05","17.06","17.07","17.08"]
}
]
}
In the data.service.ts I have the http request and it store values on :
stream$: Observable<ImpiantoModel[]>;
here my definition of the model:
#impianto.model
export class ImpiantoModel {
nomeImpianto: string;
descrImpianto: string;
posizione: string;
dati_status: string;
unita_misura: string;
vel_attuale: number;
vel: VelocitaModel[];
orario: OrariModel[];
}
#orari.model.ts
export class OrariModel {
orario: string;
}
#velocita.model.ts
export class VelocitaModel{
vel : number;
}
is it the right why to define my object?
How can I use the array "vel" and "orario"?
How can I print (access) the array "vel" of machine with "nomeImpianto" = "MFL1" ?
and how can I copy the array "vel" on new array?
thank you very much!
Here is what I understood of what you want to do : get the item in your json resp and put it in your object , so the best way is to create a static method directly when you get the json response, before returning the value create this adapter adaptImpiant(jsonObj) which will do something like :
adaptImpiant(jsonObj) {
let impiantTab = [];
jsonObj.ImpiantiProva.forEach((item) => {
let impiantoModel = {};
// impiantoModel = item if the model (below) match the item;
// if not manually set all your var like your velocita
let velocita = [] // is an array or an object with an array
// if class velocita = {}
velocita = item.vel.slice(0);
// if class velocita.valuesTab = item.vel.slice(0);
impiantoModel.velocita = velocita;
impiantTab.push(impiantoModel);
}
}
Your model seems wrong in this case, because you already use a ImpiantoModel array, so just create a class with whatever you want in :
#impianto.model
export class ImpiantoModel {
nomeImpianto: string;
descrImpianto: string;
posizione: string;
dati_status: string;
unita_misura: string;
vel_attuale: number;
vel: VelocitaModel // or simply [];
orario: OrariModel // or simply [];
}
I'm not sure I understand you, but I'll try.
is it the right why to define my object?
It should be:
export class ImpiantoModel {
nomeImpianto: string;
descrImpianto: string;
posizione: string;
dati_status: string;
unita_misura: string;
vel_attuale: number;
vel: Array<string>;
orario: Array<string>;
}
(But I have to confess, I don't know why model and not an interface)
How can I use the array "vel" and "orario"?
What do you mean?
How can I print (access) the array "vel" of machine with
"nomeImpianto" = "MFL1"
const thisContainsTheDataFromVel = whereYourDataIsStored['ImpiantiProva'].find((item) => { item['nomeImpianto'] === 'MFL1'})['vel'];
and how can I copy the array "vel" on new array?
UPDATE after reading your comment under this answer:
I took code from your example and added what you are missing. I made it so it can be more reusable (it can be enhanced even more, but I hope you understand the code and do what you need).
copyArray(data, targetValue) {
const mfl1Data = data.find((item) => item['nomeImpianto'] === targetValue);
if (mfl1Data) {
return mfl1Data.vel;
}
return [];
}
getdata2() {
this.http.get<ImpiantoModel[]>(this.myUrl)
.subscribe(
data => {
this.variableToStoreIn = this.copyArray(data, 'MFL1');
data.forEach(item => {
this.sub$.next(item);
});
});
return this.sub$;
}
CopyArray finds the data and returns it. If you don't want it like this, but just set a value of some property to the value of vel array then you can change it to:
copyArray(data) {
const mfl1Data = data.find((item) => item['nomeImpianto'] === targetValue);
if (mfl1Data) {
this.yourVariable = mfl1Data.vel;
}
}
If this answer is sufficient, please consider to mark it as the best answer, thank you.
According to your model classes, your JSON is wrong. You should have something like this:
{ "ImpiantiProva": [
{
"nomeImpianto":"MFL1",
"descrImpianto":"Multifilo 1",
"posizione":"Place1",
"dati_status": "true",
"unita_misura": "m/s",
"vel_attuale": 11.5,
"vel": [
{
"vel": 24.5
},
{
"vel": 13.6
}
...
],
"orario": [
{
"orario": "17.05"
},
{
"orario": "17.06"
}
...
]
}
]
}
Your model expects ImpiantoModel.vel and ImpiantoModel.orario to be arrays of objects. In your JSON response one is an array of numbers and the other of strings.
An if you want to use it in an HTML template, considering that you have a class attribute in your .ts file like this:
private impiantoModels: ImpiantoModel[];
You could do something like this inside your .html template:
<div *ngFor="let impModel of impiantoModels">
...
<div *ngFor="let v of impModel.vel">
<p>{{v.vel}}</p>
</div>
<div *ngFor="let o of impModel.orario">
<p>{{o.orario}}</p>
</div>
</div>

get value of a property from array of objects [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 6 years ago.
I'm building angular2 app with TypeScript and i came across a problem (note that i'm a noob in angular2 and typescript).
Problem is identical to this: From an array of objects, extract value of a property as array but since i'm not using JavaScript, provided solution isn't very helpful (or is it?)
I'm getting JSON objects from API and simply save them in array:
constructor(private namelistService: NameListService) { }
getAllDevices(){
this.namelistService.getDevices()
.subscribe(
data => this.devices = data,
error => console.log('Server error'),
);
}
also my simple service:
constructor(private http:Http){}
getDevices(): Observable<any>{
return this.http.get("http://link-to-api")
.map( (res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
resulting in objects like this (i deleted the values):
{
"_id": "",
"info": {
"device_id": ,
"device_name": "",
"uid": "",
"firmware": "",
"hardware": "",
"description": ""
},
All i want to do is to get the _id values from every object in array and save it in seperate array:
arr2 = [id1, id2, id3, id4, ... ]
You can pretty much use any javascript code inside a typescript code since typescript is compiled into javascript itself.
constructor(private namelistService: NameListService) { }
resultArray:any;
getAllDevices(){
this.namelistService.getDevices()
.subscribe(
(data) => {
this.devices = data;
this.resultArray = this.devices.map(function(a) {return a["_id"];});
},
error => console.log('Server error'),
);
}

Map json Array in static method (Angular2+TS)

Problem to get the syntax right to map my incoming data in a static method. My json Array looks like this:
[
{
"documents": [
{
"title": "+1 (film)",
"is-saved": false,
"abstract": "some text",
"id": "_1__film_",
"url": "some url"
}
]
}
]
Each item in that array is a Result.
As an example to refer to Mapping one Result I know how to do:
static resultFromJSON(json): Result {
let documents: SearchQueryDocument[] =
json.documents.map(doc => new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url))
return new Result(documents)
}
But I need to map the whole array, so how do I do that?
static resultsFromJSON(json): Result[] {
let results: Result =
json.map ... // what here?
}
Mapping one result I can use json.documents.map... but mapping the whole array it has no "name" to use...
Maybe a stupid question from a newbie, but any help is appreciated!
If I understand you correctly then your json corresponds to the following interfaces:
interface IDocument {
title: string;
"is-saved": boolean;
"abstract": string;
id: string;
url: string;
}
interface IResult {
documents: Document[];
}
And then you have an array of Result.
To map that json you can do:
static resultsFromJSON(json): Result[] {
return json.map(obj => {
new Result(obj.documents.map(doc => {
return new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url);
}));
});
}
The solution that worked for me was just a slight change to the above static method by Nitzan Tomer.
This worked:
static resultsFromJSON(json): Result[] {
return json.map(obj =>
new Result(obj.documents.map(doc =>
new SearchQueryDocument(doc.title, doc.issaved, doc.abstract, doc.id, doc.url)
))
)
}

print attributes values from JSON array in Angular2

I'm using Angular2 and I have retrieved some data from Firebase in this way:
dataset: any;
onGetData() {
this._dataService.getAllData()
.subscribe(
data => this.dataset = JSON.stringify(data),
error => console.error(error)
);
if I print dataset I get this JSON:
{"-KE8XuCI7Vsm1jKDJIGK":{"content":"aaa","title":"bbb"},"-KE8XvM268lWhXWKg6Rx":{"content":"cccc","title":"dddd"}}
How can I print out a list made up of only the title values from this JSON array?
I'd like to have: bbb - dddd
You can only iterate over an array using ngFor. In your case you need to implement a custom pipe to iterate over keys of an object.
Something like that:
#Pipe({name: 'keyValues'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]);
}
return keys;
}
}
and use it like that:
<span *ngFor="#entry of dataset | keyValues">
Title: {{entry.value.title}}
</span>
See this question for more details:
How to display json object using *ngFor
In your view you need
<div *ngFor='#data of dataset'>
{{ data.title }} -
</div>

Resources