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

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'),
);
}

Related

How to use condition with Vuejs with array and v-for?

I have an array file load with Axios, the problem is in this have an array that has image and video and I can't change it, I want to just the array that has only image, can someone please help to do that, thank you~
{
"data": [
{
"id": "01",
"media_type": "IMAGE",
"media_url": "https://...",
},
{
"id": "02",
"media_type": "VIDEO",
"media_url": "https://...",
},
{
"id": "02",
"media_type": "IMAGE",
"media_url": "https://...",
},
...
]
}
<div class="xx" v-for="event in events.data.slice(0, 6)" v-if="event.media_type == 'IMAGE'">
<img :src="event.media_url" :alt="event.caption">
</div>
data() {
return {
insta: "gram",
events: []
}
},
created() {
axios
.get('https:...')
.then(response => {
this.events = response.data
})
.catch(error => {
console.log('There is an error: ' + error.response)
})
},
You shouldn't really be mixing v-for and v-if directives, because they are confusing, officially discouraged both in Vue2 and Vue3, and most importantly, they have different precedence in Vue2 vs Vue3.
If you want to work off a filtered array (in this case, you want images only), then create a computed prop that is based off the original data. From your code it is not clear if you want to perform which operation first:
Getting the first 6 entries
Getting only images
Let's say you want to get all images, and then return the first 6 images, then this will work:
computed: {
filteredEvents() {
return this.events.data.filter(d => d.media_type === 'IMAGE').slice(0,6);
}
}
If you want to get any 6 first entries and then filter them by image, then simply switch the chaining around:
computed: {
filteredEvents() {
return this.events.data.slice(0,6).filter(d => d.media_type === 'IMAGE');
}
}
Then you can use this in your template:
<div class="xx" v-for="event in filteredEvents">
<img :src="event.media_url" :alt="event.caption">
</div>

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);

Converting a typescript class object with dictionary to a JSON array

After some digging I decided my backend needed to consume duplicate keys and as a consequence my frontend can no longer send a dictionary as a JSON string.
See my previous question.
After applying the solution provided
let mediatagRequest = new MediaTagRequest(tags);
const headers = { 'content-type': 'application/json' }
let jsonObject = {};
for (let entry of mediatagRequest.tags.entries())
{
jsonObject[entry[0]] = entry[1];
}
const body = JSON.stringify({
tags: jsonObject
});
My current output (which is what I then wanted)
{
"tags": {
"city": "Karachi"
}
However my needs have changed and after a bit of of struggle I couldn't get my desired output to be like this
{
"tags": [
{
"key": "city",
"value": "Karachi"
},
{
"key": "city",
"value": "Mumbai"
}
]
}
Could someone help, thank you.
To get your desired output you could use the Object.entries() function to get the key, value pairs separately. This code segment will turn an object into a list of objects with key value pairs:
test_object = {
karachi: "dubai",
mumbao: "moscow",
};
output = Object.entries(test_object).map(([key, value]) => ({ key, value}));
console.log(output);
You can adapt this code to select the desired parts of your object and format them as you like. There are other Object functions you can see in the documentation.

Reading JSON into arrays in Angular (HttpClient)

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}
})
})

this.http.get('....../contacts.json') - property 'map' does not exist on type 'observable<object>'

i try to get my contacts-array loaded and want to loop them.
The problem is, that i receive the contacts as an object and not as an array, so i can't use .map.
This is my code snippet:
loadConJSON() {
this.http.get('../../assets/data/contacts.json')
.map(res => res.json())
This results in the following error:
Property 'map' does not exist on type 'observable<object>'
This is the content of contacts.json:
{
"data": [
{
"_objectInstance": {
"id": 383,
"name": {
"givenName": "",
"honorificSuffix": "",
"formatted": "Schmidt",
"middleName": "",
"familyName": "Schmidt",
"honorificPrefix": ""
}, ...
How can convert the object into an array?
EDIT:
I want to do something like this (build new array):
let contactsArray = contacts.map(contacts =>
({ id: contacts.id,
familyName: contacts.name.familyName,
email: contacts.email.value }));
Try adding the following line on top of your code:
import 'rxjs/add/operator/map';
Alternatively, use pipeable operators, which are recommended since recent versions of Angular/RxJS.

Resources