mapping 2-D array in react-native - javascript

Attached JSON:-
[
{
"category":"Faces",
"items": [
{
"name": "Oh well!",
"art" : "¯\\_(ツ)_/¯"
},
{
"name": "Disapproving Look",
"art": "ಠ_ಠ"
},
{
"name": "Disapproving Look 2",
"art": "ఠ_ఠ"
},
{
"name": "Glasses Smile",
"art": "ʘ‿ʘ"
},
{
"name": "Devious Smile",
"art": "ಠ‿ಠ"
},
{
"name": "Frowning",
"art": "ಠ╭╮ಠ"
},
{
"name": "Yelling",
"art": "ಠoಠ"
},
{
"name": "Mustache Man",
"art": "ಠ▃ಠ"
},
{
"name": "Blank Stare",
"art": "ರ_ರ"
},
{
"name": "HUH?",
"art": "ლ(`ー´ლ)"
},
{
"name": "Rosy Cheeks",
"art": "(。◕‿◕。)"
},
{
"name": "hehehe",
"art": "( ¬‿¬)"
},
{
"name": "Pointing Out",
"art": "☜(⌒▽⌒)☞"
},
{
"name": "Haha!",
"art": "☜(゚ヮ゚☜)"
},
{
"name": "Run Away Crying",
"art": "ε=ε=ε=┌(;*´Д`)ノ"
},
{
"name": "Cheers",
"art": "( ^_^)o自自o(^_^ )"
},
{
"name": "Up All Night",
"art": "۞_۞"
},
{
"name": "High",
"art": "q(❂‿❂)p"
},
{
"name": "Dazed & Confused",
"art": "⊙﹏⊙"
},
{
"name": "No Clue!",
"art": "¯\\_(⊙︿⊙)_/¯"
},
{
"name": "I Dunno",
"art": "¯\\(°_o)/¯ "
},
{
"name": "Staring Eyes",
"art": "Ꙭ"
},
{
"name": "Cat Eyes",
"art": "ф_ф"
},
{
"name": "Winking",
"art": "◕‿↼"
},
{
"name": "Reaching Down",
"art": "(,,Ծ‸Ծ,,)"
},
{
"name": "Just Woke up",
"art": "╰(´・`)ノ"
},
{
"name": "Sleep Walking",
"art": "(¬º-°)¬"
},
{
"name": "Disappointed Look",
"art": "(-_-)"
}
]
},
{
"category": "Emotions",
"items": [
{
"name": "Angry",
"art": "{{|└(>o< )┘|}}"
},
{
"name": "Why, God, WHY!?",
"art": "щ(゚Д゚щ)"
},
{
"name": "In Love",
"art": "♥(。✿‿✿。)❤"
},
{
"name": "In Love 2",
"art": "♥‿♥"
},
{
"name": "Puzzled",
"art": "く(^_・)ゝ"
},
{
"name": "Mad",
"art": "( ゚Д゚)"
},
{
"name": "Whatever",
"art": "(^~^)ノ"
},
{
"name": "Happy",
"art": "ヽ(´▽`)/"
},
{
"name": "Love at First Sight",
"art": "꒰♡ˊ͈ ु꒳ ूˋ͈꒱.⑅*♡"
},
{
"name": "Need A Hug",
"art": "ヽ(´ー`)ノ"
},
{
"name": "So Beautiful!",
"art": "ಥ_ಥ"
},
{
"name": "Sad / Crying",
"art": "ಥ﹏ಥ"
},
{
"name": "Embarrased",
"art": "(﹡⌒▽⌒﹡)"
},
{
"name": "Extra Embarrased",
"art": "(/ω\)"
},
{
"name": "No Thanks",
"art": "(ღ˘⌣˘ღ)"
},
{
"name": "I've Seen The Light",
"art": "•✞_✞•"
}
]
},]
Attempt in React-Native
class Textables extends Component{
constructor(){
super()
this.state={data:[]}
}
getData(){
return fetch('https://raw.githubusercontent.com/OTGApps/Textables/master/resources/content.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount(){
this.getData();
}
render()
{
let articles= this.state.data.map(function(articleData, index){
let articles1 = articleData.map(function(meow, j){
return(<content>
<Card><CardItem><Body>
<Text>{meow.items.name}</Text></Body></CardItem></Card>
<Card><CardItem><Body>
<Text>{meow.items.art}</Text></Body></CardItem></Card></content>
);
});
return(
<Card><CardItem><Body>
<Text>{articleData.category}</Text></Body></CardItem></Card>
);
});
return(
<Content>
{articles}
</Content>
)
}
}
Error:- undefined is not a function (evaluating 'articleData.map')
I'm trying to map the the items one by one by looping through each array.
Should I use index.map instead of articleData.map?

articleData points to the object in the data array. It looks like:
{
"category": "Emotions",
"items": [],
}
You want to use articleData.items.map.
Additionally, that getData function will probably not work how you want. Since it's not bound to the class scope, it won't be able to access this.setState. You'll probably want to either add this to your constructor:
this.getData = this.getData.bind(this)
or, you can change the function declaration:
getData = () => { /* your function */ }

Related

How to update a value in a complex fhirBundle JSON?

Given a bewildering fhir document like https://raw.githubusercontent.com/Notarise-gov-sg/api-notarise-healthcerts/master/test/fixtures/v2/pdt_art_with_nric_unwrapped.json
I need to update the part the JSON from { "id": "NRIC-FIN", "value": "S9098989Z" } to { "id": "NRIC-FIN", "value": "foobar" } and then emit the whole JSON again with that change.
I just about know how to access the value.
const fs = require("fs");
let rawdata = fs.readFileSync("pdt_art_with_nric_unwrapped.json");
let art = JSON.parse(rawdata);
let nric = art.fhirBundle.entry
.flatMap((entry) => entry.resource)
.find((entry) => entry.resourceType === "Patient")
.identifier.find((entry) => entry.id === "NRIC-FIN").value;
console.log(nric);
Though I am puzzled how to update this value since it's so difficult to access. Am I missing a trick? I don't want to use regex btw!
You seem to be very close - why not just set .value using the syntax you already have...?
const fs = require("fs");
let rawdata = fs.readFileSync("pdt_art_with_nric_unwrapped.json");
let art = JSON.parse(rawdata);
let nric = art.fhirBundle.entry
.flatMap((entry) => entry.resource)
.find((entry) => entry.resourceType === "Patient")
.identifier.find((entry) => entry.id === "NRIC-FIN").value = 'foobar';
console.dir(art.fhirBundle.entry)
... results in:
[
{
"fullUrl": "urn:uuid:ba7b7c8d-c509-4d9d-be4e-f99b6de29e23",
"resource": {
"resourceType": "Patient",
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-nationality",
"extension": [
{
"url": "code",
"valueCodeableConcept": {
"text": "Patient Nationality",
"coding": [
{
"system": "urn:iso:std:iso:3166",
"code": "SG"
}
]
}
}
]
}
],
"identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{
"id": "NRIC-FIN",
"value": "foobar"
}
],
"name": [
{
"text": "Tan Chen Chen"
}
],
"gender": "female",
"birthDate": "1990-01-15"
}
},
{
"fullUrl": "urn:uuid:7729970e-ab26-469f-b3e5-36a42ec24146",
"resource": {
"resourceType": "Observation",
"specimen": {
"type": "Specimen",
"reference": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae"
},
"performer": [
{
"type": "Practitioner",
"reference": "urn:uuid:3dbff0de-d4a4-4e1d-98bf-af7428b8a04b"
},
{
"id": "LHP",
"type": "Organization",
"reference": "urn:uuid:fa2328af-4882-4eaa-8c28-66dab46950f1"
}
],
"identifier": [
{
"id": "ACSN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "ACSN",
"display": "Accession ID"
}
]
},
"value": "123456789"
}
],
"category": [
{
"coding": [
{
"system": "http://snomed.info/sct",
"code": "840539006",
"display": "COVID-19"
}
]
}
],
"code": {
"coding": [
{
"system": "http://loinc.org",
"code": "97097-0",
"display": "SARS-CoV-2 (COVID-19) Ag [Presence] in Upper respiratory specimen by Rapid immunoassay"
}
]
},
"valueCodeableConcept": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "260385009",
"display": "Negative"
}
]
},
"effectiveDateTime": "2020-09-28T06:15:00Z",
"status": "final"
}
},
{
"fullUrl": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae",
"resource": {
"resourceType": "Specimen",
"subject": {
"type": "Device",
"reference": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777"
},
"type": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "697989009",
"display": "Anterior nares swab"
}
]
},
"collection": {
"collectedDateTime": "2020-09-27T06:15:00Z"
}
}
},
{
"fullUrl": "urn:uuid:3dbff0de-d4a4-4e1d-98bf-af7428b8a04b",
"resource": {
"resourceType": "Practitioner",
"name": [
{
"text": "Dr Michael Lim"
}
],
"qualification": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "MCR",
"display": "Practitioner Medicare number"
}
]
},
"identifier": [
{
"id": "MCR",
"value": "123456"
}
],
"issuer": {
"type": "Organization",
"reference": "urn:uuid:bc7065ee-42aa-473a-a614-afd8a7b30b1e"
}
}
]
}
},
{
"fullUrl": "urn:uuid:bc7065ee-42aa-473a-a614-afd8a7b30b1e",
"resource": {
"resourceType": "Organization",
"name": "Ministry of Health (MOH)",
"type": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/organization-type",
"code": "govt",
"display": "Government"
}
]
}
],
"contact": [
{
"telecom": [
{
"system": "url",
"value": "https://www.moh.gov.sg"
},
{
"system": "phone",
"value": "+6563259220"
}
],
"address": {
"type": "physical",
"use": "work",
"text": "Ministry of Health, 16 College Road, College of Medicine Building, Singapore 169854"
}
}
]
}
},
{
"fullUrl": "urn:uuid:fa2328af-4882-4eaa-8c28-66dab46950f1",
"resource": {
"resourceType": "Organization",
"name": "MacRitchie Medical Clinic",
"type": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/organization-type",
"code": "prov",
"display": "Healthcare Provider"
}
],
"text": "Licensed Healthcare Provider"
}
],
"contact": [
{
"telecom": [
{
"system": "url",
"value": "https://www.macritchieclinic.com.sg"
},
{
"system": "phone",
"value": "+6561234567"
}
],
"address": {
"type": "physical",
"use": "work",
"text": "MacRitchie Hospital, Thomson Road, Singapore 123000"
}
}
]
}
},
{
"fullUrl": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777",
"resource": {
"resourceType": "Device",
"type": {
"coding": [
{
"system": "https://covid-19-diagnostics.jrc.ec.europa.eu/devices",
"code": "1232",
"display": "Abbott Rapid Diagnostics, Panbio COVID-19 Ag Rapid Test"
}
]
}
}
}
]
... clearly showing foobar set as you seem to desire. (Feel free to test with this Repl.it).
To "emit the full JSON" again you would just re-stringify it:
let fullJSON = JSON.stringify(art);
Instead of traversing the object manually you can use library like Jsonpath:
function replace() {
data = JSON.parse(data);
jsonpath.apply(data,
'$.fhirBundle.entry[?(#.resource.resourceType == "Patient")].resource.identifier[?(#.id == "NRIC-FIN")].value',
function(value) {
document.body.innerHTML += `value=${value}<br>`;
return 'foobar';
});
document.body.innerHTML += `updated JSON:<br> <pre>${JSON.stringify(data, undefined, 2)}</pre`;
}
let data =
`{
"id": "340139b0-8e92-4ed6-a589-d54730f52963",
"version": "pdt-healthcert-v2.0",
"type": "ART",
"validFrom": "2021-08-24T04:22:36.062Z",
"fhirVersion": "4.0.1",
"fhirBundle": {
"resourceType": "Bundle",
"type": "collection",
"entry": [
{
"fullUrl": "urn:uuid:ba7b7c8d-c509-4d9d-be4e-f99b6de29e23",
"resource": {
"resourceType": "Patient",
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-nationality",
"extension": [
{
"url": "code",
"valueCodeableConcept": {
"text": "Patient Nationality",
"coding": [
{ "system": "urn:iso:std:iso:3166", "code": "SG" }
]
}
}
]
}
],
"identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{ "id": "NRIC-FIN", "value": "S9098989Z" }
],
"name": [{ "text": "Tan Chen Chen" }],
"gender": "female",
"birthDate": "1990-01-15"
}
},
{
"fullUrl": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae",
"resource": {
"resourceType": "Specimen",
"subject": {
"type": "Device",
"reference": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777"
},
"type": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "697989009",
"display": "Anterior nares swab"
}
]
},
"collection": { "collectedDateTime": "2020-09-27T06:15:00Z" }
}
}
]
},
"issuers": [
{
"id": "did:ethr:0xE39479928Cc4EfFE50774488780B9f616bd4B830",
"revocation": { "type": "NONE" },
"name": "SAMPLE CLINIC",
"identityProof": {
"type": "DNS-DID",
"location": "donotverify.testing.verify.gov.sg",
"key": "did:ethr:0xE39479928Cc4EfFE50774488780B9f616bd4B830#controller"
}
}
],
"$template": {
"name": "HEALTH_CERT",
"type": "EMBEDDED_RENDERER",
"url": "https://healthcert.renderer.moh.gov.sg/"
}
}`
replace();
<script src="https://cdn.jsdelivr.net/npm/jsonpath#1.1.1/jsonpath.min.js"></script>
If you are flat out replacing values without any other logic, and in case if you decide to use RegEx, then you can use String.replace().
let data =
`{ "identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{ "id": "NRIC-FIN", "value": "S9098989Z" }
],
"name": [{ "text": "Tan Chen Chen" }],
"gender": "female",
"birthDate": "1990-01-15"
}
}`
let targetId = 'NRIC-FIN';
let find = new RegExp(`(?<=${targetId}.*value":\\s*").*?(?=")`, 'ig');
data = data.replace(find, 'foobar');;
document.write(`<pre>${data}</pre>`);
Note: In the regular expression, I have used i flag for case insensitive search. Used g flag to replace all occurrences of the id. If the id is unique and there is going to be only one occurrence in entire .json file then don't use g flag.

How to create dynamic lists from a json in javascript?

I am retrieving data with the following structure from a REST API
job_execs =
[{
"build_id": 12,
"job": {
"name": "test_job"
},
"product": {
"name": "new_product"
},
"time_start": "2017-08-29T01:01:19.314000-07:00",
"time_end": "2017-08-29T01:17:07.990000-07:00",
"status": {
"name": "SUCCESS"
},
"stage_executions": [{
"stage": {
"name": "stage-checkout"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 119,
"time_start": "2017-08-29T01:16:43.901000-07:00"
},
{
"stage": {
"name": "stage-wiki"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 14225,
"time_start": "2017-08-29T01:16:29.599000-07:00"
},
{
"stage": {
"name": "stage-upload"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 14225,
"time_start": "2017-08-29T01:16:29.599000-07:00"
}
]
},
{
"build_id": 13,
"job": {
"name": "test_job"
},
"product": {
"name": "new_product"
},
"time_start": "2017-08-29T01:01:19.314000-07:00",
"time_end": "2017-08-29T01:17:07.990000-07:00",
"status": {
"name": "SUCCESS"
},
"stage_executions": [{
"stage": {
"name": "stage-checkout"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 400,
"time_start": "2017-08-29T01:16:43.901000-07:00"
},
{
"stage": {
"name": "stage-wiki"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 34,
"time_start": "2017-08-29T01:16:29.599000-07:00"
},
{
"stage": {
"name": "stage-upload"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 250,
"time_start": "2017-08-29T01:16:29.599000-07:00"
}
]
}
]
What I'm trying to do is drill into the stage executions per job and generate a list per stage name. I want to loop through every job and append the duration_millis to the appropriate stage list.
So taking the JSON I posted above, I would want the following lists created:
['stage_checkout', 119, 400]
['stage_wiki', 14225, 34]
['stage_upload', 1215, 250]
How do I accomplish this?
Any pointers or even a starting point would help.
This might work, I have broken it down to simple functions so you can understand what is happening here.
var job_execs =
[{
"build_id": 12,
"job": {
"name": "test_job"
},
"product": {
"name": "new_product"
},
"time_start": "2017-08-29T01:01:19.314000-07:00",
"time_end": "2017-08-29T01:17:07.990000-07:00",
"status": {
"name": "SUCCESS"
},
"stage_executions": [{
"stage": {
"name": "stage-checkout"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 119,
"time_start": "2017-08-29T01:16:43.901000-07:00"
},
{
"stage": {
"name": "stage-wiki"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 14225,
"time_start": "2017-08-29T01:16:29.599000-07:00"
},
{
"stage": {
"name": "stage-upload"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 14225,
"time_start": "2017-08-29T01:16:29.599000-07:00"
}
]
},
{
"build_id": 13,
"job": {
"name": "test_job"
},
"product": {
"name": "new_product"
},
"time_start": "2017-08-29T01:01:19.314000-07:00",
"time_end": "2017-08-29T01:17:07.990000-07:00",
"status": {
"name": "SUCCESS"
},
"stage_executions": [{
"stage": {
"name": "stage-checkout"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 400,
"time_start": "2017-08-29T01:16:43.901000-07:00"
},
{
"stage": {
"name": "stage-wiki"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 34,
"time_start": "2017-08-29T01:16:29.599000-07:00"
},
{
"stage": {
"name": "stage-upload"
},
"status": {
"name": "SUCCESS"
},
"duration_millis": 250,
"time_start": "2017-08-29T01:16:29.599000-07:00"
}
]
}
]
const func = (arr) => {
var ch = {};
arr.map(ar => {
ar.stage_executions.map((s) => {
ch[s.stage.name] = [];
})
})
return ch;
}
const func2 = (arr) => {
var all = func(arr);
for(var k in all) {
arr.map((ar) => {
ar.stage_executions.map((st) => {
if (st.stage.name === k) {
all[k].push(st.stage.name, st.duration_millis)
}
})
})
}
return all;
}
const func3 = (arr) => {
const all = func2(arr);
for(var key in all) {
all[key] = [...new Set(all[key])]
}
return all;
}
console.log(func3(job_execs))
This code sample might help you. As well i changed the invalid JSON to a valid one and hope this is still matching your data basis.
job_execs = [{"build_id":12,"job":{"name":"test_job"},"product":{"name":"new_product"},"time_start":"2017-08-29T01:01:19.314000-07:00","time_end":"2017-08-29T01:17:07.990000-07:00","status":{"name":"SUCCESS"},"stage_executions":[{"stage":{"name":"stage-checkout"},"status":{"name":"SUCCESS"},"duration_millis":119,"time_start":"2017-08-29T01:16:43.901000-07:00"},{"stage":{"name":"stage-wiki"},"status":{"name":"SUCCESS"},"duration_millis":14225,"time_start":"2017-08-29T01:16:29.599000-07:00"},{"stage":{"name":"stage-upload"},"status":{"name":"SUCCESS"},"duration_millis":14225,"time_start":"2017-08-29T01:16:29.599000-07:00"}]},{"build_id":13,"job":{"name":"test_job"},"product":{"name":"new_product"},"time_start":"2017-08-29T01:01:19.314000-07:00","time_end":"2017-08-29T01:17:07.990000-07:00","status":{"name":"SUCCESS"},"stage_executions":[{"stage":{"name":"stage-checkout"},"status":{"name":"SUCCESS"},"duration_millis":400,"time_start":"2017-08-29T01:16:43.901000-07:00"},{"stage":{"name":"stage-wiki"},"status":{"name":"SUCCESS"},"duration_millis":34,"time_start":"2017-08-29T01:16:29.599000-07:00"},{"stage":{"name":"stage-upload"},"status":{"name":"SUCCESS"},"duration_millis":250,"time_start":"2017-08-29T01:16:29.599000-07:00"}]}]
var aCheckout = ['stage-checkout'];
var aWiki = ['stage-wiki'];
var aUpload = ['stage-upload'];
job_execs.forEach(function (build) {
build.stage_executions.forEach(function (stage) {
switch(stage.stage.name){
case "stage-checkout":
aCheckout.push(stage.duration_millis);
break;
case "stage-wiki":
aWiki.push(stage.duration_millis);
break;
case "stage-upload":
aUpload.push(stage.duration_millis);
break;
}
});
})
console.log(aCheckout, aWiki, aUpload);

Complex JSON structure with JS

I'm looking for a way to generate an HTML table from a JSON data.
I'm limitated with tooling options because we use CMS, so I can only use JS, JQuery and ApacheVelocity (without making new templates, only using the 'syntax').
Well, I get this kind of JSON data from remote API:
{
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
The first problem I face are those numeric indexes.
The only way to make reference to this is like this:
arr_from_json.data.data.region[123].game[11844220].team1_name
It is ok if we only have a few "games" extracted, even 100 games. But it is impossible to keep it updated with thousands of games who are constantly being updated.
Is there some way for iterarte through this ugly JSON structure?
Many thanks
Edit:
I want to create a table with the distinct games:
Zorya Luhansk - SC Braga
W1 X W2
2.39 3.01 2.82
Most important data/keys to me are: both team names, name of the possible outcome and price.
You can convert those indexed objects into traditional arrays using a helper function, then iterate over the data in a more natural way after transforming it. See below for an example using Array.map and the helper function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
const resp = {
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
function parseGameData(data){
return keysToArray(data.region).map(obj => keysToArray(obj.game).map(obj => {
obj.market = keysToArray(obj.market).map(obj => {
return {
name: obj.name,
event: keysToArray(obj.event)
}
})
return obj
}))
}
console.log(parseGameData(resp.data.data))

Javascript marge and slice json

Based on this array json I need to merge it constantly.
Using push() I get this kind of result
JSON
**0:**{
"net_drops.vpn0": {
"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}
},
"named_local.view_resolver_numfetch__default": {
"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}
}
}
**1:**{
"net_drops.vpn0": {
"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}
},
"named_local.view_resolver_numfetch__default": {
"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}
}
}
...
But I need this kind of result
JSON
{
"net_drops.vpn0": {
**0:**{"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}},
**1:**{"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}}
},
"named_local.view_resolver_numfetch__default": {
**0:**{"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}},
**1:**{"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}}
}
...
}
It's possible? If yes how can I do it?
Then I need to slice the objects based on last_update, if the last_update is older than 30 minutes of current time is sliced
Eg: current time 10:00:00, object last_update 09:31:00 is sliced.
It's possible? If yes how can I do it?
Best regards
Looks like you are combining the data with the same key.
To achieve that result, loop through the original JSON data and push it to another array by key. In your case the keys are: 'net_drops.vpn0' and 'named_local.view_resolver_numfetch__default' like: array.net_drops.vpn0 = json_data
For the slicing based on the 'last_updated' key, you can try to use array.filter function. Check this LINK for reference.

Looping through an object not giving me other languages

I have three JSON statements below that I have turned into a JavaScript object. I want to print out the actor, verb and object for each of these statements. I'm having trouble with the object.definition.name because sometimes it will appear in other languages. Because of this and the way I have it coded now, it gives me "undefined" for the second statement because the second statement is fr-FR and not en-US. How can I modify the object part of my loop so it gives me an object no matter what language it is?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Get Statements 1 demo</title>
<script src="xapiwrapper.min.js"></script>
</head>
<body>
<p id='demo'></p>
<script>
var obj1 =
{
"statements": [{
"verb": {
"id": "http://adlnet.gov/expapi/verbs/initialized",
"display": {
"en-US": "initialized"
}
},
"version": "1.0.0",
"timestamp": "2017-05-25T13:01:49.439248+00:00",
"object": {
"definition": {
"extensions": {
"http://example.com": 12
},
"name": {
"en-US": "Change management app"
}
},
"id": "https://www.avimegiddo.com/wp-admin/admin-ajax.php?action=h5p_embed&id=12",
"objectType": "Activity"
},
"actor": {
"mbox": "mailto:john.doe#abc.com",
"name": "John Doe",
"objectType": "Agent"
},
"stored": "2017-05-25T13:01:49.439248+00:00",
"authority": {
"mbox": "mailto:tom.creighton.ctr#adlnet.gov",
"name": "tom",
"objectType": "Agent"
},
"id": "2b03bcd0-11bd-4b43-a256-7e7c8cb259fc"
},
{
"verb": {
"id": "http://adlnet.gov/expapi/verbs/attempted",
"display": {
"en-US": "attempted"
}
},
"version": "1.0.0",
"timestamp": "2017-05-25T12:54:52.184309+00:00",
"object": {
"definition": {
"extensions": {
"http://h5p.org/x-api/h5p-local-content-id": 12
},
"name": {
"fr-FR": "le livre"
}
},
"id": "https://www.avimegiddo.com/wp-admin/admin-ajax.php?action=h5p_embed&id=12",
"objectType": "Activity"
},
"actor": {
"mbox": "mailto:sally.smith#abc.com",
"name": "Sally Smith",
"objectType": "Agent"
},
"stored": "2017-05-25T12:54:52.184309+00:00",
"authority": {
"mbox": "mailto:megiddo#gmail.com",
"name": "avimegiddo",
"objectType": "Agent"
},
"context": {
"contextActivities": {
"category": [{
"id": "http://h5p.org/libraries/H5P.DragText-1.5",
"objectType": "Activity"
}],
"grouping": [{
"definition": {
"moreInfo": "https://www.avimegiddo.com/business-emails/",
"type": "http://activitystrea.ms/schema/1.0/page",
"name": {
"en": "How to write business emails: be formal and polite. ESL / EFL Practice Quizzes."
}
},
"id": "https://www.avimegiddo.com/business-emails/"
}]
}
},
"id": "83105145-a27c-4bec-bbb0-c1c9f9775930"
},
{
"verb": {
"id": "http://adlnet.gov/expapi/verbs/attempted",
"display": {
"en-US": "attempted"
}
},
"version": "1.0.0",
"timestamp": "2017-05-25T13:51:45.976631+00:00",
"object": {
"definition": {
"extensions": {
"http://h5p.org/x-api/h5p-local-content-id": 5,
"http://h5p.org/x-api/h5p-subContentId": "bb5c8621-1bcf-4cc7-b1b0-8af2950bffcd"
},
"name": {
"en-US": "Drag the words into the correct boxes\n"
}
},
"id": "https://www.avimegiddo.com/wp-admin/admin-ajax.php?action=h5p_embed&id=5?subContentId=bb5c8621-1bcf-4cc7-b1b0-8af2950bffcd",
"objectType": "Activity"
},
"actor": {
"mbox": "mailto:terry.phillips#abc.com",
"name": "Terry Phillips",
"objectType": "Agent"
},
"stored": "2017-05-25T13:51:45.976631+00:00",
"authority": {
"mbox": "mailto:megiddo#gmail.com",
"name": "avimegiddo",
"objectType": "Agent"
},
"context": {
"extensions": {
"http://id.tincanapi.com/extension/ending-point": 1
},
"contextActivities": {
"category": [{
"id": "http://h5p.org/libraries/H5P.DragText-1.5",
"objectType": "Activity"
}],
"parent": [{
"id": "https://www.avimegiddo.com/wp-admin/admin-ajax.php?action=h5p_embed&id=5",
"objectType": "Activity"
}],
"grouping": [{
"definition": {
"moreInfo": "https://www.avimegiddo.com/2017/04/21/business-emails-short-quizzes/",
"type": "http://activitystrea.ms/schema/1.0/page",
"name": {
"en": "Projects ~ Avi Megiddo"
}
},
"id": "https://www.avimegiddo.com/2017/04/21/business-emails-short-quizzes/"
}]
}
},
"id": "7b0582d3-c22d-4818-937e-cc0e5ffbbf18"
}
]
}
var actorVerbObject = "";
for (i=0; i<3; i++){
actorVerbObject += obj1.statements[i].actor.name + ", " + obj1.statements[i].verb.display['en-US'] + ", " + obj1.statements[i].object.definition.name['en-US'] + "<br />";
}
document.getElementById('demo').innerHTML = actorVerbObject;
</script>
</body>
</html>
Use Object.keys See this fiddle
var actorVerbObject = "";
for (i = 0; i < 3; i++) {
var displayLangs = Object.keys(obj1.statements[i].verb.display);
var definitionLangs = Object.keys(obj1.statements[i].object.definition.name);
actorVerbObject += obj1.statements[i].actor.name + ", " + obj1.statements[i].verb.display[displayLangs[0]] + ", " + obj1.statements[i].object.definition.name[definitionLangs[0]] + "<br />";
}

Categories

Resources