How to Read Multiple dimensional JavaScript Object in AngularJS - javascript

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>

Related

nest items in JSON based on value?

Trying to get my head around this one..
Incoming data looks like:
[
{
"value": {
"label": "MZ Algal bloom",
"type": "case",
"incident": {
"name": "Algal bloom"
},
"personName": "Lionel Carter"
}
},
{
"value": {
"label": "BW Algal bloom",
"type": "case",
"incident": {
"name": "Algal bloom"
},
"personName": "Jerome Yost"
}
},
{
"value": {
"label": "Detergent",
"type": "case",
"incident": null,
"personName": "Jerald Legros"
}
}
]
I would like to transform this into
[
{
"label": "Algal bloom",
"children": [
{ "label": "Lionel Carter", "type": "case"},
{ "label": "Jerome Yost", "type": "case" }]
},
{ "label": "Detergent", "type": "case" }
]
Basically, the rule is that if incident is not NULL then the incident name becomes the parent and the children hold the personName - otherwise we simply pass through the label and type. I can walk the array and switch out the label with the incident name, but I'm not sure how to group up the incidents..
It's basic grouping with an exception for elements without incident.
You can group the elements without incident in a separate group:
const data = [{"value": {"label": "MZ Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Lionel Carter"}},{"value": {"label": "BW Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Jerome Yost"}},{"value": {"label": "Detergent","type": "case","incident": null,"personName": "Jerald Legros"}}];
function group(data) {
const result = data.reduce((acc, { value }) => {
if (!value.incident) {
acc.ungrouped.push({ label: value.label, type: value.type });
} else {
if (!acc.groups[value.incident.name]) acc.groups[value.incident.name] = { label: value.incident.name, children: [] };
acc.groups[value.incident.name].children.push({ label: value.personName, type: value.type });
}
return acc;
}, { groups: {}, ungrouped: [] });
return [...Object.values(result.groups), ...result.ungrouped];
}
console.log(group(data));

Delete all JSON keys nested having specific name

I want to delete all occurances of keynames like etag,formattedType and metadata in the object using dynamic iteration of whole object
var myjson {
"etag": "%EiIBAgMFBgcICQoLDA0ODxATFBUWGSEiIyQlJicuNTc9Pj9AGgECIdgxQTUREdTBneFMzZz0=",
"names": [{
"unstructuredName": "Natalie Victor",
"displayNameLastFirst": "Victor, Natalie",
"familyName": "Victor",
"displayName": "Natalie Victor",
"givenName": "Natalie",
"metadata": {
"source": {
"id": "c8de0718a7c3458",
"type": "CONTACT"
},
"primary": true
}
}],
"photos": [{
"metadata": {
"primary": true,
"source": {
"id": "c8de0718a7c3458",
"type": "CONTACT"
}
},
"url": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAdAA/V8BNOaftJmdYPfvspCwKr2nuTmSEuXTHowCLcDEAEiGQoBThD___________8BGKjbxPr______wE/s100/photo.jpg",
"default": true
}],
"memberships": [{
"metadata": {
"source": {
"type": "CONTACT",
"id": "c8de0718a7c3458"
}
},
"contactGroupMembership": {
"contactGroupId": "6a68e3a408126601",
"contactGroupResourceName": "contactGroups/6a68e3a408126601"
}
}, {
"contactGroupMembership": {
"contactGroupId": "myContacts",
"contactGroupResourceName": "contactGroups/myContacts"
},
"metadata": {
"source": {
"id": "c8de0718a7c3458",
"type": "CONTACT"
}
}
}],
"phoneNumbers": [{
"value": "6767674765",
"formattedType": "Home",
"canonicalForm": "+916767674765",
"metadata": {
"primary": true,
"source": {
"id": "c8de0718a7c3458",
"type": "CONTACT"
}
},
"type": "home"
}],
"emailAddresses": [{
"type": "home",
"formattedType": "Home",
"value": "nati_a_j#hotmail.com",
"metadata": {
"source": {
"id": "c8de0718a7c3458",
"type": "CONTACT"
},
"primary": true
}
}],
"biographies": [{
"contentType": "TEXT_PLAIN",
"value": "Email: ssww#gmail.com\nName.Last: Victor\nName.First: Natalie\nPhone: 6767674765",
"metadata": {
"primary": true,
"source": {
"id": "c8de0718a7c3458",
"type": "CONTACT"
}
}
}],
"resourceName": "people/c904625878430659672"
}
I only know to use delete key by names such as
delete myjson.etag
delete myjson.names[0].metadata
How do I iterate the complete json since some of the json has arrays and nested structures which are not known in advance.
Hence a remove_keys(myjson, ["etag","memberships","formattedType","metadata"]) should render a result
var myjson {
"names": [{
"unstructuredName": "Natalie Victor",
"displayNameLastFirst": "Victor, Natalie",
"familyName": "Victor",
"displayName": "Natalie Victor",
"givenName": "Natalie",
}],
"photos": [{
"url": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAdAA/V8BNOaftJmdYPfvspCwKr2nuTmSEuXTHowCLcDEAEiGQoBThD___________8BGKjbxPr______wE/s100/photo.jpg",
"default": true
}],
"phoneNumbers": [{
"value": "6767674765",
"canonicalForm": "+916767674765",
"type": "home"
}],
"emailAddresses": [{
"type": "home",
"value": "nati_a_j#hotmail.com",
}],
"biographies": [{
"contentType": "TEXT_PLAIN",
"value": "Email: ssww#gmail.com\nName.Last: Victor\nName.First: Natalie\nPhone: 6767674765",
}],
"resourceName": "people/c904625878430659672"
}
You need a recursive function for this task:
function filter(obj: any, list: string[]) {
if (obj && typeof obj === 'object') {
for (let item in obj) {
if (list.includes(item)) {
delete obj[item];
} else {
if (Array.isArray(obj[item])) {
for (let el of obj[item]) {
filter(el, list);
}
} else {
filter(obj[item], list);
}
}
}
}
return obj;
}
// example usage:
let a = {b: 5, c: 6, d: { a: 1, b: 2}}
filter(a, ['b']);
console.log(a);
Conversely, it may be faster in some interpreters to rebuild the object, rather than delete keys.
function removeKeys(obj, keys) {
if (Array.isArray(obj))
return obj.map(v => removeKeys(v, keys))
else if (typeof obj == "object" && obj != null) {
const _obj = {}
Object.keys(obj).forEach(k => {
if(!keys.includes(k)) _obj[k] = removeKeys(obj[k], keys)
})
return _obj
}
else
return obj
}
console.log(removeKeys(myjson, ["etag","memberships","formattedType","metadata"]))
this recursive function will solve your problem
var myjson = {
"etag":"%EiIBAgMFBgcICQoLDA0ODxATFBUWGSEiIyQlJicuNTc9Pj9AGgECIdgxQTUREdTBneFMzZz0=",
"names":[
{
"unstructuredName":"Natalie Victor",
"displayNameLastFirst":"Victor, Natalie",
"familyName":"Victor",
"displayName":"Natalie Victor",
"givenName":"Natalie",
"metadata":{
"source":{
"id":"c8de0718a7c3458",
"type":"CONTACT"
},
"primary":true
}
}
],
"photos":[
{
"metadata":{
"primary":true,
"source":{
"id":"c8de0718a7c3458",
"type":"CONTACT"
}
},
"url":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAdAA/V8BNOaftJmdYPfvspCwKr2nuTmSEuXTHowCLcDEAEiGQoBThD___________8BGKjbxPr______wE/s100/photo.jpg",
"default":true
}
],
"memberships":[
{
"metadata":{
"source":{
"type":"CONTACT",
"id":"c8de0718a7c3458"
}
},
"contactGroupMembership":{
"contactGroupId":"6a68e3a408126601",
"contactGroupResourceName":"contactGroups/6a68e3a408126601"
}
},
{
"contactGroupMembership":{
"contactGroupId":"myContacts",
"contactGroupResourceName":"contactGroups/myContacts"
},
"metadata":{
"source":{
"id":"c8de0718a7c3458",
"type":"CONTACT"
}
}
}
],
"phoneNumbers":[
{
"value":"6767674765",
"formattedType":"Home",
"canonicalForm":"+916767674765",
"metadata":{
"primary":true,
"source":{
"id":"c8de0718a7c3458",
"type":"CONTACT"
}
},
"type":"home"
}
],
"emailAddresses":[
{
"type":"home",
"formattedType":"Home",
"value":"nati_a_j#hotmail.com",
"metadata":{
"source":{
"id":"c8de0718a7c3458",
"type":"CONTACT"
},
"primary":true
}
}
],
"biographies":[
{
"contentType":"TEXT_PLAIN",
"value":"Email: ssww#gmail.com\nName.Last: Victor\nName.First: Natalie\nPhone: 6767674765",
"metadata":{
"primary":true,
"source":{
"id":"c8de0718a7c3458",
"type":"CONTACT"
}
}
}
],
"resourceName":"people/c904625878430659672"
}
function removeKeys(obj,keys){
if(Array.isArray(obj)){
obj.forEach(innerObj=>{
removeKeys(innerObj,keys)
})
}else{
keys.forEach(k=>{
delete obj[k];
})
Object.keys(obj).forEach(key=>{
if(typeof obj[key]=='object'){
removeKeys(obj[key],keys)
}
})
}
}
removeKeys(myjson, ["etag","memberships","formattedType","metadata"])
console.log(myjson);

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>

SOAP text value to Objects

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

Inserting select into array Angular-Schema-Form

I am trying to make an array, where each element contains select. My code right now:
angular.module('MaterialAidForm', ['schemaForm']).controller('FormController', function($scope) {
$scope.schema = {
"type": "object",
"title": "Comment",
"required": [
"comments"
],
"properties": {
"comments": {
"type": "array",
"items": {
"type": "object",
"properties": {
"spam": {
"title": "Spam",
"type": "select",
"titleMap":
{
"a": "A",
"b": "B"
}
}
},
"required": [
"name",
"comment"
]
}
}
}
};
$scope.form = ["*"];
$scope.model = {};
});
But when I open browser, I only see array without selector inside.

Categories

Resources