Retrieving a specific data from the JSON data provided - javascript

How do I retrieve the 'name' and 'description' from the JSON data below? I have tried in my code (see below) but couldn't figure it out. Do I use an array to retrieve the name and description from the JSON data?
{
"status": {
"timestamp": "2020-10-14T09:04:56.382Z",
"error_code": 0,
"error_message": null,
"elapsed": 8,
"credit_count": 1,
"notice": null
},
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"category": "coin",
"description": "Bitcoin (BTC) is a cryptocurrency . Users are able to generate BTC through the process of mining. Bitcoin has a current supply of 18,516,718. The last known price of Bitcoin is 11,440.13537699 USD and is down -0.18 over the last 24 hours. It is currently trading on 9569 active market(s) with $22,842,507,797.43 traded over the last 24 hours. More information can be found at https://bitcoin.org/.",
"slug": "bitcoin",
"logo": "https://s2.coinmarketcap.com/static/img/coins/64x64/1.png",
"subreddit": "bitcoin",
"notice": "",
"tags": [
"mineable",
"pow",
"sha-256",
"store-of-value",
"state-channels"
],
"tag-names": [
"Mineable",
"PoW",
"SHA-256",
"Store of Value",
"State channels"
],
"tag-groups": [
"OTHER",
"CONSENSUS_ALGORITHM",
"CONSENSUS_ALGORITHM",
"PROPERTY",
"PROPERTY"
],
"urls": {
"website": [
"https://bitcoin.org/"
],
"twitter": [],
"message_board": [
"https://bitcointalk.org"
],
"chat": [],
"explorer": [
"https://blockchain.coinmarketcap.com/chain/bitcoin",
"https://blockchain.info/",
"https://live.blockcypher.com/btc/",
"https://blockchair.com/bitcoin",
"https://explorer.viabtc.com/btc"
],
"reddit": [
"https://reddit.com/r/bitcoin"
],
"technical_doc": [
"https://bitcoin.org/bitcoin.pdf"
],
"source_code": [
"https://github.com/bitcoin/"
],
"announcement": []
},
"platform": null,
"date_added": "2013-04-28T00:00:00.000Z",
"twitter_username": "",
"is_hidden": 0
}
}
}
import React, { useEffect, useState } from 'react';
import Axios from 'axios'
import { Link } from 'react-router-dom';
function DetailsScreen(props){
const [cryptoVar, setcryptoList] = useState({name: "", description: ""});
useEffect(() => {
Axios.get(`http://localhost:5000/api/getProducts/${props.match.params.id}`,
{
}).then((response)=>{
console.log(response.data.data );
setcryptoList({
name: response.data.data,
description: response.data.data
});
}).catch(err =>{
console.log(err.response.data);
})
return () => {
}
}, [])
console.log(cryptoVar.description);
return(
<div>
Name: {cryptoVar.name}
Description: {cryptoVar.description}
</div>
);
}
export default DetailsScreen;

Related

React + Redux Toolkit is not able to push nested objects to an array

React + Redux Toolkit is not able to push nested objects to an array.
getting paused before potential out-of-memory crash
flow.js
import { createSlice } from "#reduxjs/toolkit";
const initialState = {
flowMessage: [],
};
export const flowSlice = createSlice({
name: "flow",
initialState,
reducers: {
setFlowMessage: (state, action) => {
state.flowMessage.push(action.payload.messages);
},
},
});
export const { setFlowMessage } = flowSlice.actions;
export default flowSlice.reducer;
store.js
import { configureStore } from '#reduxjs/toolkit'
import flowReducer from "./actions";
export const store = configureStore({
reducer: {
flow: flowReducer,
},
});
When I am pushing data to props from react component and response is nested objects.
Resonse object look like this:
{
"id": "1661751452644",
"type": "input",
"data": {
"label": "vinay kummar"
},
"children": [
{
"id": "1661885522666",
"type": "card",
"data": {
"name": "vinay",
"text": "Card Body Card Body Card Body",
"label": "default",
"links": [
{}
],
"title": "Card Title",
"header": "This is header"
},
"children": [
{
"id": "1661885522666",
"type": "card",
"data": {
"name": "vinay",
"text": "Card Body Card Body Card Body",
"label": "default",
"links": [
{}
],
"title": "Card Title",
"header": "This is header"
},
"children": []
},
{
"id": "1662223395515",
"type": "image",
"data": {
"text": "No",
"label": "",
"links": [],
"title": "",
"header": "",
"images": []
},
"children": []
},
{
"id": "1662276221551",
"type": "useraction",
"data": {
"text": "Input",
"label": "",
"links": [],
"title": "",
"header": "",
"images": [],
"node_type": "",
"user_input": "user_name"
},
"children": []
}
]
}
]
}
Component code..
componentDidMount() {
this.props.dispatch(setFlowMessage({ messages: response }));
}
Can you guys please help me out where I am making mistake?

delete an elemnt from an array inside another array with mongodb

hello everyone i have a document of materiels where each document has an array of articles and each article has an array of details here's my collection data:
{
"_id": "62f2404b42556d62e2939466",
"code": "120K",
"designation": "PIZZA",
"article": [
{
"etat": "Reçu",
"lot": "",
"marque": "Royal",
"fournisseur": "maatalah",
"dateachat": "2022-08-01T00:00:00.000Z",
"bc": null,
"bl": null,
"fc": null,
"quantite": 12,
"_id": "62f25d001a035d017369e1f8",
"detail": [
{
"serie": "12",
"ddp": "2023-01-01T00:00:00.000Z",
"_id": "62f3986fe462b8a173c7d220"
},
{
"serie": "13",
"ddp": "2023-03-01T00:00:00.000Z",
"_id": "62f39cc1862c1bf5bc40157a"
}
]
},
{
"etat": "Reçu",
"lot": "",
"marque": "margarita",
"fournisseur": "",
"dateachat": "2022-08-04T00:00:00.000Z",
"bc": null,
"bl": null,
"fc": null,
"quantite": 13,
"_id": "62f25d041a035d017369e1fb",
"detail": [
{
"serie": "12345",
"ddp": "2023-01-01T00:00:00.000Z",
"_id": "62f281158a159e976c7c68d5"
}
]
}
],
"qteglobal": 25,
"id": "62f2404b42556d62e2939466"
}
i want to remove an element from the detail array here my express js code:
const { id, idarticle, iddetail } = req.params;
const materiel = Materiel.findOneAndUpdate(
{ _id: id, "article._id": idarticle, "article.detail._id": iddetail },
{ $pull: { "article.$.detail": { _id: iddetail } } },
{ new: true }
);
there is no syntax error but the document it doesn't seem to be deleted.
Can anyone help me please ? thank you
Hello guys after trying some methods i end up with this solution:
const { id, idarticle, iddetail } = req.params;
await Materiel.findOneAndUpdate(
{
id,
"article._id": idarticle,
},
{
$pull: {
"article.$[].detail": {
_id: iddetail,
},
},
}
);

Get field of JSON in Javascript Console

I have a JSON like this, how to get the value of StatusDescription? I tried many times but the result is undefined. Here is my JSON:
{
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
I'm using in my NodeJS app, like myapp.js, and console.log()
Try this
I stored your sample json in variable json
var json = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
Accessed it like below
console.log(json.data.items[0].origin_info.trackinfo[0].StatusDescription);
Items is an array and we took array element 0.
trackinfo again is an array and we took array element 0.
We can change array index or loop through and get required values.
You have to iterate through your items and trackinfo to get to StatusDescription. Try this one.
const data = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
const items = data.data.items.map(item => item)
const trackinfo = items.map(item => item.origin_info.trackinfo).flat()
console.log(trackinfo)
const statusDescription = trackinfo.map(trackinfo => trackinfo.StatusDescription)
console.log(statusDescription)

Add JSON to empty array issue

I have a top level JSON structure as follows:
{
"video": [],
"messages": [],
"notifications": []
}
and i have a database output (in variable "result") as follows i want to push into the "video" array:
[
{
"_id": "5f98ab906439155cfc6f9afb",
"status": "NOT_STARTED",
"date": "2020-10-27T23:21:52.683Z",
"callInvitees": [
{
"username": "user1"
},
{
"username": "user2"
}
]
},
{
"_id": "5f98aba0789e163e0c78908f",
"status": "NOT_STARTED",
"date": "2020-10-27T23:22:08.048Z",
"callInvitees": [
{
"username": "user1"
}
]
}
]
My code is:
let dashboardJSON = { "video": [], "messages": [], "notifications": [] };
dashboardJSON.video.push(result)
It works but i am ending up with too many arrays (i think) - it looks as follows:
{
"video": [
[
{
"_id": "5f98ab906439155cfc6f9afb",
"status": "NOT_STARTED",
"date": "2020-10-27T23:21:52.683Z",
"callInvitees": [
{
"username": "user1"
},
{
"username": "user2"
}
]
},
{
"_id": "5f98aba0789e163e0c78908f",
"status": "NOT_STARTED",
"date": "2020-10-27T23:22:08.048Z",
"callInvitees": [
{
"username": "user1"
}
]
}
]
],
"messages": [],
"notifications": []
}
I want "video": [ { ... }, { ... } ] whereas i have "video": [[ { ... }, { ... } ]]
How can i resolve this?
You can use the spread operator as follows:
let result = [
{
"_id": "5f98ab906439155cfc6f9afb",
"status": "NOT_STARTED",
"date": "2020-10-27T23:21:52.683Z",
"callInvitees": [
{
"username": "user1"
},
{
"username": "user2"
}
]
},
{
"_id": "5f98aba0789e163e0c78908f",
"status": "NOT_STARTED",
"date": "2020-10-27T23:22:08.048Z",
"callInvitees": [
{
"username": "user1"
}
]
}
]
let dashboardJSON = { "video": [], "messages": [], "notifications": [] };
dashboardJSON.video.push(...result)
console.log(dashboardJSON);
Just use Array.prototype.map() method. Map method returns a new array with the result by using the provided function.
const ret = {
video: [],
messages: [],
notifications: [],
};
const data = [
{
_id: '5f98ab906439155cfc6f9afb',
status: 'NOT_STARTED',
date: '2020-10-27T23:21:52.683Z',
callInvitees: [
{
username: 'user1',
},
{
username: 'user2',
},
],
},
{
_id: '5f98aba0789e163e0c78908f',
status: 'NOT_STARTED',
date: '2020-10-27T23:22:08.048Z',
callInvitees: [
{
username: 'user1',
},
],
},
];
ret.video = data.map((x) => x);
console.log(ret);

How to take the body from response coming in console and assign to particular objects in angular4

I have a set of links, i need to read each link and assign to its particular object.
TS:
exportUrl: any = {
patient: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Patient/Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
medication: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/MedicationOrder?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
condition: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Condition?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
allergy: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/AllergyIntolerance?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
immunization: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Immunization?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
diagnostic: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/DiagnosticReport?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
observation: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Observation?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB&code=8310-5",
procedure: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Procedure?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
device: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Device?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
careplan: "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/CarePlan?patient=Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB"
};
constructor(private http: Http) {}
ngOnInit() {
this.http.get(this.exportUrl.patient).subscribe(data => {
console.log('data', data);
})
Here i am not able to get data._body it throws an error in code
Working link:
https://stackblitz.com/edit/angular-z9vwzq?file=src/app/app.component.ts
Console:
{
"resourceType": "Patient",
"birthDate": "1985-08-01",
"active": true,
"gender": "male",
"deceasedBoolean": false,
"id": "Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB",
"careProvider": [{
"display": "Physician Family Medicine",
"reference": "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Practitioner/T3Mz3KLBDVXXgaRoee3EKAAB"
}],
"name": [{
"use": "usual",
"text": "Jason Argonaut",
"family": ["Argonaut"],
"given": ["Jason"]
}],
"identifier": [{
"use": "usual",
"system": "urn:oid:1.2.840.114350.1.13.327.1.7.5.737384.0",
"value": "E3826"
}, {
"use": "usual",
"system": "urn:oid:1.2.3.4",
"value": "203579"
}],
"address": [{
"use": "home",
"line": ["1979 Milky Way Dr."],
"city": "Verona",
"state": "WI",
"postalCode": "53593",
"country": "US"
}, {
"use": "temp",
"line": ["5301 Tokay Blvd"],
"city": "MADISON",
"state": "WI",
"postalCode": "53711",
"country": "US",
"period": {
"start": "2011-08-04T00:00:00Z",
"end": "2014-08-04T00:00:00Z"
}
}],
"telecom": [{
"system": "phone",
"value": "608-271-9000",
"use": "home"
}, {
"system": "phone",
"value": "608-771-9000",
"use": "work"
}, {
"system": "phone",
"value": "608-771-9000",
"use": "mobile"
}, {
"system": "fax",
"value": "608-771-9000",
"use": "home"
}, {
"system": "phone",
"value": "608-771-9000",
"use": "temp",
"period": {
"start": "2011-08-04T00:00:00Z",
"end": "2014-08-04T00:00:00Z"
}
}, {
"system": "email",
"value": "open#epic.com"
}],
"maritalStatus": {
"text": "Single",
"coding": [{
"system": "http://hl7.org/fhir/ValueSet/marital-status",
"code": "S",
"display": "Never Married"
}]
},
"communication": [{
"preferred": true,
"language": {
"text": "English",
"coding": [{
"system": "urn:oid:2.16.840.1.113883.6.99",
"code": "en",
"display": "English"
}]
}
}],
"extension": [{
"url": "http://hl7.org/fhir/StructureDefinition/us-core-race",
"valueCodeableConcept": {
"text": "Asian",
"coding": [{
"system": "2.16.840.1.113883.5.104",
"code": "2028-9",
"display": "Asian"
}]
}
}, {
"url": "http://hl7.org/fhir/StructureDefinition/us-core-ethnicity",
"valueCodeableConcept": {
"text": "Not Hispanic or Latino",
"coding": [{
"system": "2.16.840.1.113883.5.50",
"code": "2186-5",
"display": "Not Hispanic or Latino"
}]
}
}, {
"url": "http://hl7.org/fhir/StructureDefinition/us-core-birth-sex",
"valueCodeableConcept": {
"text": "Male",
"coding": [{
"system": "http://hl7.org/fhir/v3/AdministrativeGender",
"code": "M",
"display": "Male"
}]
}
}]
}
You can use the text method to get response body in text like:
data.text()
and if you want response body in json then use json method like:
data.json()
ngOnInit() {
this.http.get(this.exportUrl.patient).subscribe(data => {
console.log(data.text());
console.log(data.json());
})
You could convert the body of the response to a string with text() and assign that to whatever:
ngOnInit() {
this.http.get(this.exportUrl.patient).subscribe(data => {
let body = data.text();
})
If you want to get your data in json format then you can use data.json()
ngOnInit() {
this.http.get(this.exportUrl.patient).subscribe(data => {
console.log('data', data.json());
})
Working example is here - https://stackblitz.com/edit/angular-knd3cq
Before explaining the solution you are using angular 4 with Http. Http is deprecated in angular 4 in favor to HttpClient. You will need to update your module definition first.
import {NgModule} from '#angular/core';
import {BrowserModule} from '#angular/platform-browser';
// Import HttpClientModule from #angular/common/http
import {HttpClientModule} from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module
// after BrowserModule.
HttpClientModule, // <- not HttpModule
],
})
export class MyAppModule {}
Then you will need to inject HttpClient instead of Http
constructor(private http: HttpClient) {}
Then you can do:
this.http.get(this.exportUrl.patient).subscribe(data => {
// Read the result field from the JSON response.
console.log(data['resourceType']); // should log Patient
});
But the best things to do is to use typechecking response. First you need to create an interface representing you JSON like:
export interface Patient {
active: boolean;
resourceType: string;
// ...
}
And update your code to:
this.http.get<Patient>(this.exportUrl.patient).subscribe(data => {
console.log(data.resourceType); // should log Patient
});
Then to respect good practice a component shouldn't access HttpClient but it should request data through a Service

Categories