Looping through an object not giving me other languages - javascript

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 />";
}

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.

Lookup Value in JSON using Javascript

I'm very new to Javascript and have been given a task. I have a JSON feed that has been given as follows:
var data = {
"feeds": {
"regions": [{
"name": "Lichtenberg",
"id": "01408.b",
"suburbs": [{
"name": "Fennpfuhl",
"views": 76400
},
{
"name": "Lichtenberg",
"views": 87895
},
{
"name": "Rummelsberg",
"views": 10239
}
]
},
{
"name": "Mitte",
"id": "03442.f",
"suburbs": [{
"name": "Tiergarten",
"views": 82695
},
{
"name": "Mitte",
"views": 67234
},
{
"name": "Hansaviertel",
"views": 10848
},
{
"name": "Moabit",
"views": 67500
}
]
},
{
"name": "Friedrichshain-Kreuzberg",
"id": "01991.o",
"suburbs": [{
"name": "Friedrichshain",
"views": "98494"
},
{
"name": "Kreuzberg",
"views": "27800"
}
]
},
{
"name": "Templehof-Schöneberg",
"id": "01778.k",
"suburbs": [{
"name": "Friedenau",
"views": 76595
},
{
"name": "Schöneberg",
"views": 20731
},
{
"name": "Templehof",
"views": 58000
},
{
"name": "Mariendorf",
"views": 32300
}
]
},
{
"name": "Pankow",
"id": "02761.q",
"suburbs": [{
"name": "Wießensee",
"views": 81294
},
{
"name": "Prenzlauer Berg",
"views": 76470
},
{
"name": "Pankow",
"views": 90210
}
]
}
],
"branding": [{
"municipality_id": "01408.b",
"brand_color": "#f9cd90"
}, {
"municipality_id": "03442.f",
"brand_color": "#F28123"
}, {
"municipality_id": "01991.o",
"brand_color": "#D34E24"
}, {
"municipality_id": "01778.k",
"brand_color": "#563F1B"
}, {
"municipality_id": "02761.q",
"brand_color": "#38726C"
}],
"customer": {
"name": "Viktoria Tiedemann",
"date_of_birth": "1981-09-19",
"address": {
"street": "Schönfließer Str 9",
"suburb": "Prenzlauer Berg",
"postcode": "10439"
}
}
}
};
The task is simple - to find the suburb and the region of Viktoria Tiedemann. So far I've tried using the below:
var customer_suburb;
var customer_name = 'Viktoria Tiedemann';
for (var i = 0; i < data.feeds.customer.length; i++){
if (data.feeds.customer.name[i] == customer_name){
customer_suburb = data.feeds.customer.address.suburb;
}
}
but it keeps on returning undefined values - where am I going wrong? I'm thinking to use the same process to get the region.
In your data, you have just one customer — not an array of customers — which is accessible with:
data.feeds.customer
( if customer was supposed to be an array, you could find Viktoria with : let customer = data.feeds.customer.find(c => c.name === 'Viktoria Tiedemann') )
You can get the suburb with:
let suburb = data.feeds.customer.address.suburb
Once you have that, you just need to find() the region whose suburbs array has this. For that find() combined with some() does this succinctly:
var data = {"feeds": {"regions": [{"name": "Lichtenberg","id": "01408.b","suburbs": [{ "name": "Fennpfuhl", "views": 76400 },{ "name": "Lichtenberg", "views": 87895 },{ "name": "Rummelsberg", "views": 10239 }]},{"name": "Mitte","id": "03442.f","suburbs": [{ "name": "Tiergarten", "views": 82695 },{ "name": "Mitte", "views": 67234 },{ "name": "Hansaviertel", "views": 10848 },{ "name": "Moabit", "views": 67500 }]},{"name": "Friedrichshain-Kreuzberg","id": "01991.o","suburbs": [{ "name": "Friedrichshain", "views": "98494" },{ "name": "Kreuzberg", "views": "27800" }]},{"name": "Templehof-Schöneberg","id": "01778.k", "suburbs": [{ "name": "Friedenau", "views": 76595 },{ "name": "Schöneberg", "views": 20731 },{ "name": "Templehof", "views": 58000 },{ "name": "Mariendorf", "views": 32300 }]},{"name": "Pankow","id": "02761.q","suburbs": [{ "name": "Wießensee", "views": 81294 },{ "name": "Prenzlauer Berg", "views": 76470 },{ "name": "Pankow", "views": 90210 }]}],"branding": [{"municipality_id": "01408.b","brand_color": "#f9cd90"},{"municipality_id": "03442.f","brand_color": "#F28123"},{"municipality_id": "01991.o","brand_color": "#D34E24"},{"municipality_id": "01778.k","brand_color": "#563F1B"},{"municipality_id": "02761.q","brand_color": "#38726C"}],"customer": {"name": "Viktoria Tiedemann","date_of_birth": "1981-09-19","address": {"street": "Schönfließer Str 9","suburb": "Prenzlauer Berg","postcode": "10439"}}}};
let suburb = data.feeds.customer.address.suburb
let region = data.feeds.regions.find(region => region.suburbs.some(s => s.name === suburb))
console.log("suburb:", suburb, "region:", region.name)

mapping 2-D array in react-native

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 */ }

Javascript multiple drop down box

Is there a way to get a multiple drop down field from a list of arrays without having to hardcode the information into the HTML? So that by selecting each category the relevant subcategory will drop down.
The list looks something like this:
var listData = [
{
"title": "Meeting Room",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Book a Car",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Stationery",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Hospitality",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Communications",
"category": "News",
"url": "https://blogs.office.com/"
},
{
"title": "Industries",
"category": "News",
"url": "https://blogs.office.com/"
},
{
"title": "Policy",
"category": "News",
"url": "https://blogs.office.com/"
},
{
"title": "Get started",
"category": "Information",
"url": "https://support.office.com/"
},
{
"title": "What do you need",
"category": "Useful Information",
"url": "https://support.office.com/"
},
{
"title": "Accessibility features",
"category": "Useful Information",
"url": "https://support.office.com/"
},
{
"title": "Videos",
"category": "Useful Information",
"url": "https://support.office.com/"
}
]
The following code does the work. It's vanilla JS.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Form</title>
</head>
<body>
<select id="categories" onchange="changeCategory(event)"> </select>
<select id="title"> </select>
<select id="url"> </select>
<script>
var listData = [{
"title": "Meeting Room"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Book a Car"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Stationery"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Hospitality"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Communications"
, "category": "News"
, "url": "https://blogs.office.com/"
}, {
"title": "Industries"
, "category": "News"
, "url": "https://blogs.office.com/"
}, {
"title": "Policy"
, "category": "News"
, "url": "https://blogs.office.com/"
}, {
"title": "Get started"
, "category": "Information"
, "url": "https://support.office.com/"
}, {
"title": "What do you need"
, "category": "Useful Information"
, "url": "https://support.office.com/"
}, {
"title": "Accessibility features"
, "category": "Useful Information"
, "url": "https://support.office.com/"
}, {
"title": "Videos"
, "category": "Useful Information"
, "url": "https://support.office.com/"
}];
function removeOptions(selectbox) {
var i;
for (i = selectbox.options.length - 1; i >= 0; i--) {
selectbox.remove(i);
}
}
function changeCategory(event) {
removeOptions(document.getElementById('title'))
removeOptions(document.getElementById('url'))
mySelect1 = document.getElementById('title')
mySelect2 = document.getElementById('url');
listData.forEach(function (item, index) {
if (item.category == event.target.value) {
mySelect1.options[mySelect1.options.length] = new Option(item.title, item.title);
mySelect2.options[mySelect2.options.length] = new Option(item.url, item.url);
}
});
}
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
var mySelect = document.getElementById('categories');
var categories = new Array;
listData.forEach(function (item, index) {
if (!categories.contains(item.category)) {
mySelect.options[mySelect.options.length] = new Option(item.category, item.category);
categories.push(item.category);
}
});
</script>
</body>
</html>

Passing function argument to retrieve data from an object

I am have some trouble with a script I am working on. I have been provided with an object with multiple items from a product catalog.
What I am trying to do is to write a function which to which will allow me to render this data easily.
<script type="application/javascript">
SKUinfo =
{
"s238554": {
"Age": {
"Description": "Age 18+",
"Thumbnail": "/productImages/assets/img/icon18.gif"
},
"Barcode": {
"Barcode": "50622132430794"
},
"Currency": "£",
"Description": "Description goes here",
"Id": 44305,
"Packshots": [
"/productImages/238556/1min.jpg",
"/productImages/238556/2med.jpg",
"/productImages/238556/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Xbox 360",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1392940800000+0000)/",
"Screenshots": [
{
"ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
"ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
}
],
"Title": "Product title 2 goes here",
"Variants": [
{
"Id": 58242,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 29.97,
"PriceCultureFormat": "29.97",
"PriceWithCurrencyFormat": "£29.97",
"Sku": 238556,
"Type": {
"Description": "New"
}
},
],
"Vendor": {
"Description": ""
},
},
"s238556": {
"Age": {
"Description": "Age 18+",
"Thumbnail": "/productImages/assets/img/pegi/icon18.gif"
},
"Barcode": {
"Barcode": "5060134530794"
},
"Currency": "£",
"Description": "Description here",
"Id": 654654,
"Packshots": [
"/productImages/238556/1min.jpg",
"/productImages/238556/2med.jpg",
"/productImages/238556/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "PlayStation 3",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1392940800000+0000)/",
"Screenshots": [
{
"ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
"ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
},
{
"ScreenshotMax": "/productImages/238556/7scrmax2.jpg",
"ScreenshotMin": "/productImages/238556/6scrmin2.jpg"
},
],
"Title": "Product title 2 goes here",
"Variants": [
{
"Id": 58242,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 29.97,
"PriceCultureFormat": "29.97",
"PriceWithCurrencyFormat": "£29.97",
"Sku": 238556,
"Type": {
"Description": "New"
}
},
],
"Vendor": {
"Description": ""
},
"VideoHTML": "html here",
"status": {
"Response": "product found",
"Success": true
}
}
}
</script>
The above example is the output I get for two products.
If I try to get access to this data this is where I have a problem
<script type="application/javascript">
function getSKU(s)
{
console.log(SKUinfo.s.Title);
}
getSKU(s238554);
</script>
I imagine this is being caused when I am passing the argument s back to the function getSKU a the node selection in the data object. In this I would expect the console output to be the Title from SKU s238554.
What I get however, is: Uncaught ReferenceError: s238554 is not defined
I would appreciate any guidance that can be offered as I am a javascript novice.
Access your property by used[] on SKUinfo.s.Title like SKUinfo[s].Title
And also pass your property name within the quotes 's238554' as it's not variable.
Something like this.
function getSKU(s){
console.log(SKUinfo[s].Title);
}
getSKU('s238554'); // s238554 within quotes.

Categories

Resources