SOAP text value to Objects - javascript

I am using the node package xml-js to convert a SOAP response to json.
The text element response I got in two different requests are detailed below.
How do I change the response in each cases?
1.
Response
{
"declaration": {
"attributes": {
"version": "1.0",
"encoding": "utf-8"
}
},
"elements": [
{
"type": "element",
"name": "Envelope",
"attributes": {
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema"
},
"elements": [
{
"type": "element",
"name": "Body",
"elements": [
{
"type": "element",
"name": "FetchCustResponse",
"attributes": {
"xmlns": "http://DC_API/vproxy/"
},
"elements": [
{
"type": "element",
"name": "FetchCustResult",
"elements": [
{
"type": "text",
"text": "00_AccountNo: 242734005790, AccountType: 1, Address: Cell:340397882, Balance: 0.00, ContactNo: Cell:01039788200, MeterNo: 11178005790, MinAmount: 11,715.40, Name: David James"
}
]
}
]
}
]
}
]
}
]
}
Desired output for the text element value
"text" : {
"AccountNo": "04278005790",
"AccountType": "1",
"Address": "08039788217",
"Balance": "0.00",
"ContactNo": "08039788217",
"MeterNo": "04278005790",
"MinAmount": "11,715.40",
"Name": "David James"
}
2.
Response
{
"declaration": {
"attributes": {
"version": "1.0",
"encoding": "utf-8"
}
},
"elements": [
{
"type": "element",
"name": "Envelope",
"attributes": {
"xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema"
},
"elements": [
{
"type": "element",
"name": "Body",
"elements": [
{
"type": "element",
"name": "FetchUsageResponse",
"attributes": {
"xmlns": "http://DC_API/vproxy/"
},
"elements": [
{
"type": "element",
"name": "FetchUsageResult",
"elements": [
{
"type": "text",
"text": "00_<NewDataSet>\r\n <Table>\r\n <ID>9872686</ID>\r\n <AccountNo>04278005790</AccountNo>\r\n <MeterNo>90278005790</MeterNo>\r\n <AccounType>1</AccounType>\r\n <PINs>5539</PINs>\r\n <TotalAmount>4900.00</TotalAmount>\r\n <CreditedAmount>4802.00</CreditedAmount>\r\n <FleetComm>9.80</FleetComm>\r\n <DealerComm>73.50</DealerComm>\r\n <BankComm>14.70</BankComm>\r\n <Date>2021-04-24T16:32:36.4+01:00</Date>\r\n <IDWebTrans>13385836</IDWebTrans>\r\n <NoOfCards>1</NoOfCards>\r\n <BUID>12</BUID>\r\n <TxnReference>BD069419</TxnReference>\r\n <Token>24559787672457451531</Token>\r\n <TokeUnit>195.70</TokeUnit>\r\n <TokenAmt>4558.14</TokenAmt>\r\n <Charges>341.86</Charges>\r\n </Table>\r\n <Table>\r\n <ID>9763409</ID>\r\n <AccountNo>04278005790</AccountNo>\r\n <MeterNo>90278005790</MeterNo>\r\n <AccounType>1</AccounType>\r\n <PINs>5539</PINs>\r\n <TotalAmount>5000.00</TotalAmount>\r\n <CreditedAmount>4900.00</CreditedAmount>\r\n <FleetComm>10.00</FleetComm>\r\n <DealerComm>75.00</DealerComm>\r\n <BankComm>15.00</BankComm>\r\n <Date>2021-04-06T12:35:17.367+01:00</Date>\r\n <IDWebTrans>13270588</IDWebTrans>\r\n <NoOfCards>1</NoOfCards>\r\n <BUID>12</BUID>\r\n <TxnReference>108969129</TxnReference>\r\n <Token>17218654018179855270</Token>\r\n <TokeUnit>118.40</TokeUnit>\r\n <TokenAmt>2520.93</TokenAmt>\r\n <Charges>2479.07</Charges>\r\n </Table>\r\n</NewDataSet>"
}
]
}
]
}
]
}
]
}
]
}
Desired output for the text element value
Array of Objects
Any pointer, solutions or hints, please?

For the first problem, I wrote a function and it is working so far.
function filterDown(obj) {
const obj1 = obj.elements;
const obj2 = obj1[0];
const obj3 = obj2.elements;
const obj4 = obj3[0];
const obj5 = obj4.elements;
const obj6 = obj5[0];
const obj7 = obj6.elements;
const obj8 = obj7[0];
const obj9 = obj8.elements;
const obj10 = obj9[0];
const obj11 = obj10.text;
const obj13 = obj11.split("_");
const obj14 = obj13[1].replace("Cell:", "");
const obj15 = obj14.replace("Cell:", "");
const obj16 = obj15.split(":");
return {
AccountNo: obj16[1].replace(", AccountType", "").trim(),
AccountType: obj16[2].replace(", Address", "").trim(),
Address: obj16[3].replace(", Balance", "").trim(),
Balance: obj16[4].replace(", ContactNo", "").trim(),
ContactNo: obj16[5].replace(", MeterNo", "").trim(),
MeterNo: obj16[6].replace(", MinAmount", "").trim(),
MinAmount: obj16[7].replace(", Name", "").trim(),
Name: obj16[8].trim(),
};
}
var desiredResult = filterDown(result);

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 print huge number of items from the json array

This is my json format with that im displaying my array items like this.
If i have more items in my array mean how can i print that all using for loop or is there any method available to print all that items in an array?
{
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
}
<script>
const api_url = "API URL";
async function get_data_from_api() {
const response = await fetch(api_url);
var data = await response.json();
var track = data["workers"][2]["id"];
document.getElementById('demo2').innerHTML = track ;
}
</script>
Reference:
JSON.stringify()
const o = {
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
};
output.innerHTML = JSON.stringify(o, undefined, 2);
<pre id="output"></pre>

o["postmore"] is not iterable

I want to transform created_time from CST to ISOString(ex:2019-02-22T17:43:05.000Z), so i need to get created_time.
But I have the question. When I use for(let...of...){} , I get the error
"o.postmore is not iterable".
How to fixed the codes to get created_time and transform the time?
{
"data": [
{
"text1": "123",
"desc": "xyz",
"postmore": [
{
"name": "haha",
"created_time": "2018-08-22 18:30:01 CST+0800"
},
{
"name": "gogo",
"created_time": "2018-08-22 18:30:01 CST+0800"
}]
},
{
"text1": "123",
"desc": "hjk",
"postmore": [
{
"name": "haha",
"created_time": "2018-08-23 18:30:01 CST+0800"
},
{
"name": "gogo",
"created_time": "2018-08-23 18:30:01 CST+0800"
}]
}]
}
this.http.get(url).subscribe(res =>{
this.testapi = res["data"];
for (let o of this.testapi){
o["text1"] = parseInt(o["text1"]);
for(let os of o["postmore"]){
os["created_time"] = new Date().toISOString();
console.log(os["created_time"]);
}
};
)

How to Read Multiple dimensional JavaScript Object in AngularJS

I have the following code:
var result2 = xmljs.xml2json(response.content);
console.log(result2);
In AngularJS now I want to get value of IsError from the following JavaScript object:
{
"elements": [
{
"type": "element",
"name": "s:Envelope",
"attributes": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"elements": [
{
"type": "element",
"name": "s:Body",
"elements": [
{
"type": "element",
"name": "ValidateLoginResponse",
"attributes": {
"xmlns": "http://tempuri.org/"
},
"elements": [
{
"type": "element",
"name": "ValidateLoginResult",
"attributes": {
"xmlns:a": "http://schemas.datacontract.org/2004/07/BeehiveHrms.MobileServices",
"xmlns:i": "http://www.w3.org/2001/XMLSchema-instance"
},
"elements": [
{
"type": "element",
"name": "a:ErrorMsg",
"attributes": [
{
"type": "text",
"text": "Please enter valid username and password."
}
]
},
{
"type": "element",
"name": "a:IsError",
"elements": [
{
"type": "text",
"text": "true"
}
]
},
{
"type": "element",
"name": "a:IsActive",
"elements": [
{
"type": "text",
"text": "false"
}
]
}
]
}
]
}
]
}
]
}
]
}
It's in:
elements[0].elements[0].elements[0].elements[0].elements[1].elements[0].text
I hope it helps!
If you don't know under which elements it is located, you need a recursive search for your JSON. Pick your favourite approach and reach the children of children of all of your nodes until you find what you are searching for.
I assumed you are always looking for "name" property. Here is the demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.JSON = {
"elements": [{
"type": "element",
"name": "s:Envelope",
"attributes": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"elements": [{
"type": "element",
"name": "s:Body",
"elements": [{
"type": "element",
"name": "ValidateLoginResponse",
"attributes": {
"xmlns": "http://tempuri.org/"
},
"elements": [{
"type": "element",
"name": "ValidateLoginResult",
"attributes": {
"xmlns:a": "http://schemas.datacontract.org/2004/07/BeehiveHrms.MobileServices",
"xmlns:i": "http://www.w3.org/2001/XMLSchema-instance"
},
"elements": [{
"type": "element",
"name": "a:ErrorMsg",
"attributes": [{
"type": "text",
"text": "Please enter valid username and password."
}]
},
{
"type": "element",
"name": "a:IsError",
"elements": [{
"type": "text",
"text": "true"
}]
},
{
"type": "element",
"name": "a:IsActive",
"elements": [{
"type": "text",
"text": "false"
}]
}
]
}]
}]
}]
}]
}
// recursive function
function findNode(elem, currentNode) {
var i,
currentChild,
result;
if (elem == currentNode["name"]) { // can be a dynamic key
return currentNode;
} else {
if (currentNode["elements"]) { // can be a dynamic key
for (i = 0; i < currentNode["elements"].length; i++) {
currentChild = currentNode["elements"][i];
result = findNode(elem, currentChild);
if (result !== false) {
return result; // found
}
}
}
return false; // not found
}
}
$scope.find = function() {
var res;
res = findNode($scope.search, $scope.JSON);
if (res) {
$scope.found = angular.copy(res.elements[0]);
} else {
$scope.found = null;
}
}
$scope.search = "a:IsError";
$scope.find();
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="search" />
<button ng-click="find()">Find</button>
<br>
<code>{{search}} : {{found}}</code>
<hr>
<button ng-click="s=!s">{{s ? 'Hide' : 'Show'}} JSON</button>
<pre ng-show="s">{{JSON | json}}</pre>
</div>
</body>
</html>

Search a Javascript Object for the position of a specific ID? [duplicate]

This question already has answers here:
Find by key deep in a nested array
(21 answers)
Closed 4 years ago.
I have a Javascript object with lots of different sections. How can I search through all of the sections to find the position of a specific ID? The ID's that I am searching for are not in a specific location, and can be located in any of the tree branches.
For example, I am searching for this ID:
xobmnbjxg0g_1527269346261
And I am trying to output the position of that ID, which would be this:
app['structure'][0]['if-children'][0]['id']
My Javascript Object:
var app = {
"structure": [
{
"id": "0",
"type":"IF",
"parameters": [
{
"id": "xobmnbjxg0g_1527269346260",
"type": "field",
"value": "CV_TEST_SPOT1X"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children": [
{
"id": "xobmnbjxg0g_1527269346261",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children":[
],
"else-children":[
]
}
],
"else-children":[
{
"id": "xobmnbjxg0g_1527269346262",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children":[
{
"id":"xobmnbjxg0g_152726934626X"
}
],
"else-children":[
{
"id":"xobmnbjxg0g_152726934626Y"
}
]
}
]
},
{
"id": "xobmnbjxg0g_1527269346263",
"type":"IF",
"parameters": [
[
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
]
],
"if-children": [
{
"id": "xobmnbjxg0g_1527269346264",
"type":"IF",
"parameters": [
[
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
]
],
"if-children":[
{
"id": "xobmnbjxg0g_1527269346265",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
],
"if-children":[
{
"id":"xobmnbjxg0g_1527269346266"
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346267"
}
]
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346268"
}
]
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346269"
}
]
}
]
};
Interesting puzzle/question.
pretty sure there are some edge cases im missing but this seems to pass some tests.
function is(obj, type){
return Object.prototype.toString.call(obj) === `[object ${type}]`;
}
function findPosition(obj, mykey, myval, res){
if(is(obj, "Object")){
if(mykey in obj && obj[mykey] === myval){
res.tree.push(mykey);
res.found = true;
} else {
for( let key in obj){
if(res.found) break;
res.tree.push(key);
findPosition(obj[key], mykey, myval, res);
}
if(!res.found) res.tree.pop();
}
} else if(is(obj, "Array")){
for(let i = 0; i < obj.length; i++){
if(res.found) break;
res.tree.push(i);
findPosition(obj[i], mykey, myval, res);
}
if(!res.found) res.tree.pop();
} else {
res.tree.pop();
}
return res;
}
Usage and output
findPosition([{one: { two: [{id: [{id:'my'}]}]}}], "id", "mys", {tree:[], found: false})
> tree: Array(0), found: false}
findPosition([{one: { two: [{id: [{id:'my'}]}]}}], "id", "my", {tree:[], found: false})
> {found: true, tree: [0, "one", "two", 0, "id", 0, "id"]}
For finding if current obj you are iterating over is an Array you can also use Array.isArray

Categories

Resources