How to map json arrays in angularjs controller - angularjs

I am having problem in mapping json array in angularjs, can someone please look how can i correctly map the arrays and iterate their values. In arrays icdCode requires to be dynamic field (this is the other part i need help on) how can i achieve this correctly. thanks
Way i am mapping in Controller
$scope.preAuthorizationInfo.collections.preAuthClinicalDetailInfoFormVO.active = active;
Json arrays
"preAuthDiagnosisVOs": [
{
"preauthDiagnosisId": 165,
"diagnosisVO": {
"diagnosisId": 171,
"diagnosisCode": "Provisional",
"icdCode": {
"icdCodeId": 1,
"description": "Other intestinal Escherichia coli infections",
"icdCode": "Other intestinal Escherichia coli infections",
"icdCodeChapter": "Certain infectious and parasitic diseases",
"icdCodeCode": "A04.4"
},
"active": false
},
"active": true
},
{
"preauthDiagnosisId": 166,
"diagnosisVO": {
"diagnosisId": 172,
"diagnosisCode": "differential",
"icdCode": {
"icdCodeId": 2,
"description": "Other viral enteritis",
"icdCode": "Other viral enteritis",
"icdCodeChapter": "Certain infectious and parasitic diseases",
"icdCodeCode": "A08.3"
},
"active": false
},
"active": true
}
]
},

If You want to iterate over this object , You can use nested loop
angular.forEach(your_object.preAuthDiagnosisVOs, function(value, key) {
if (angular.isObject(value)) {
angular.forEach(value, function(value1, key) {
if (angular.isObject(value1)) {
angular.forEach(value1, function(value2, key) {
if (angular.isObject(value2)) {
angular.forEach(value2, function(value3, key) {
console.log(key + " : " + value3);
});
} else {
console.log(key + " : " + value2);
}
});
} else {
console.log(key + " : " + value1);
}
});
} else {
console.log(key + " : " + value);
}
});
And if you want just that active value just use
yourObject.preAuthDiagnosisVOs[0].active or yourObject.preAuthDiagnosisVOs[1].active
Hope this helps you . Thanks

I just validate your json format it has some syntactical issue. I have corrected this.
{
"preAuthDiagnosisVOs": [{
"preauthDiagnosisId": 165,
"diagnosisVO": {
"diagnosisId": 171,
"diagnosisCode": "Provisional",
"icdCode": {
"icdCodeId": 1,
"description": "OtherintestinalEscherichiacoliinfections",
"icdCode": "OtherintestinalEscherichiacoliinfections",
"icdCodeChapter": "Certaininfectiousandparasiticdiseases",
"icdCodeCode": "A04.4"
},
"active": false
},
"active": true
}, {
"preauthDiagnosisId": 166,
"diagnosisVO": {
"diagnosisId": 172,
"diagnosisCode": "Provisional",
"icdCode": {
"icdCodeId": 2,
"description": "Otherviralenteritis",
"icdCode": "Otherviralenteritis",
"icdCodeChapter": "Certaininfectiousandparasiticdiseases",
"icdCodeCode": "A08.3"
},
"active": false
},
"active": true
}]
}
Now to access active key . preAuthDiagnosisVOs is array to access this you have to iterate with angular forEach loop. For access active key of each index just iterate and get it or to get directly use object.preAuthDiagnosisVOs[0].active and object.preAuthDiagnosisVOs[1].active.
I think it might be help you. Thank you

Related

How to render an complex Object with nested Objects and arrays inside in React/JSX

I get this Object as a response from an API:
{
"transcript": {
"monologues": [
{
"speaker": 0,
"elements": [
{
"type": "text",
"value": "Bobby",
"ts": 2.99,
"end_ts": 3.55,
"confidence": 0.82
},
{ "type": "punct", "value": " " },
{
"type": "text",
"value": "tell",
"ts": 6.99,
"end_ts": 7.47,
"confidence": 0.74
},
{ "type": "punct", "value": " " },
{
"type": "text",
"value": "them",
"ts": 7.47,
"end_ts": 7.63,
"confidence": 0.44
},
{ "type": "punct", "value": "." }
]
}
]
}
}
How do i get "speaker" and "value" from the "elements" array?
I tried to map through the "monologues" array and then nest another map of the "elements" array like this:
{transcription.transcript?.monologues.map((monologue, i) => {
return monologue.elements.map((text, i) => {
return <p>{text.value}</p>;
});
})}
but for some reason it's not working. What am i doing wrong?
You are nesting a map() within a map(). This would result in a structure which has an array within an array.
Using your example, your end result would be something like:
[["bobby", " ", "tell", " ", "."], [/* Other monologues here if there were any*/]]
What you probably want is a flat array of the values so the flatMap function is your best friend.
This should be better:
{transcription.transcript?.monologues.flatMap((monologue, i) => {
return monologue.elements.map((text, i) => {
return <p>{text.value}</p>;
});
})}
Disclaimer: I haven't tested this code so may have to tweak it a bit if it doesn't work as is.
I just noticed that somewhere in my code i was stringifying the json response and i had to parse it back:
{JSON.parse(transcription).transcript?.monologues.map((monologue, i) => {
return monologue.elements.map((text, i) => {
return <p>{text.value}</p>;
});
})}

Angular - Convert objects in a nested array into comma seapared values before binding to grid

below is part of my JSON response coming from an API
{
"totalCount": 2,
"customAttributes": [
{
"objectType": "OWNER",
"atrributeId": 215,
"attributeName": "DATELICENSEFIRSTISSUED",
"attributeDisplayName": "DATE LICENSE FIRST ISSUED",
"dataType": "DATE",
"inputValues": [],
"isGridEligible": "true",
"isInvoiceEligible": "false"
},
{
"objectType": "LOCATION",
"atrributeId": 217,
"attributeName": "DONOTRENEW",
"attributeDisplayName": "DO NOT RENEWS",
"dataType": "Value List",
"inputValues": [
{
"id": 5,
"value": "VEHICLELISTREQUIRED"
},
{
"id": 6,
"value": "STATESWITHRECIPROCITY"
}
],
"isGridEligible": "true",
"isInvoiceEligible": "false"
}
]
}
Here, I am binding customAttributes as grid data.
this.customFieldsService.getCustomFields(this.columnList, this.pageNumber, this.pageSize, null).subscribe(res => {
if(res){
this.cfData = res;
this.gridData = {
data: this.cfData.customAttributes,
total: this.cfData.totalCount
}
}
});
Here, my problem is with inputValues column, which comes as an array of objects. I need to convert it to comma seaparated values and then bind to grid data like
"inputValues": ["VEHICLELISTREQUIRED" "STATESWITHRECIPROCITY"]
I can ignore the "id" property as we are not using it at angular side. I tried using join method but not able to solve it within the nested array. Please suggest. Thanks.
In typescript it can be done with:
const joined: string = customAttribute.inputValues
.map(x => x.value) // [{value: 'VEHICLELISTREQUIRED'}, {value: 'STATESWITHRECIPROCITY'}]
.join(' ') // "VEHICLELISTREQUIRED" "STATESWITHRECIPROCITY"
const putIntoArray = [joined]; // ["VEHICLELISTREQUIRED" "STATESWITHRECIPROCITY"]
Of course you can put the joined string immediately into an array.

How can I change the attribute in dataset of Fusionchart?

Hi I am implementing a chart in my Angularjs Application, You can see this plunker http://jsfiddle.net/fusioncharts/73xgmacm/ The thing which I want to achieve is to change the value attribute to profit. How can I do this ? I want to display profit not values.
Regards
After 2 days I finally find out the answer. The thing is You cannot change the Fusionchart attribute value but you can change the attribute of your API once you fetched. I used a loop after I fetched the API and replace the 'profit' attribute with value in this way I made the chart. Yes The thing which i had been ignoring was the use of 'variable' instead of scope. If you see this example you would understand Example Here. I am sharing my code May be it helps someone else too.
Give below is my json array which i called tps.json
[
{
"index": "1",
"variantoption": "fan-green",
"company": "sk fans",
"quantity": "650",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "2",
"variantoption": "fan-white",
"company": "al ahmed fans",
"quantity": "450",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "3",
"variantoption": "fan-purple",
"company": "asia fans",
"quantity": "350",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "4",
"variantoption": "fan-yellow",
"company": "falcon fans",
"quantity": "250",
"profit": "78296",
"loss": "8457",
"year": "2016"
}
]
and here is my controller
$http.get('js/tps.json').success(function (data) {
var chartdata = data;
var arrLength = chartdata.length;
console.log(arrLength);
for (var i = 0; i < arrLength; i++) {
if (chartdata[i]['profit'] && chartdata[i]['index']) {
chartdata[i].value = chartdata[i].profit;
delete chartdata[i].profit;
chartdata[i].label = chartdata[i].index;
delete chartdata[i].index;
console.log(chartdata);
}
}
console.log(chartdata);
FusionCharts.ready(function () {
var tps = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"showvalues": "1",
"animation": "1"
},
"data" : chartdata
}
});
tps.render();
});
}
);
}
-Stay foolish stay hungry

ForEach Loop JSON AngularJS Object in Object

I am very new to AngularJS and I am trying to learn how to get deeper into a JSON object that has objects inside of objects and sometimes even arrays. This is a "simplified" version I am working with and I hope it will help me get a basic understanding so I can do the rest on my own.
json
values = {
"profile": {
"fields": {
"number-of-fields": "700",
"inside": [
"test1",
"test2"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
}
code
angular.forEach(values, function(value, key) {
console.log(key + ': ' + value);
// I know I need to loop inside of each object I beleieve
});
http://jsfiddle.net/ygahqdge/184/
The basics
Traverse object properties with a dot ., traverse array indexes with an index reference, [0|1|2|etc.].
What about your object?
var yoObject = {
"profile": {
"fields": {
"number-of-fields": "700",
"inside": [
"test1",
"test2"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
}
Get the inside values:
// object object object array
yoObject.profile.fields.inside.map(console.log, console) // ["test1", "test2"]
Get the id:
// object property
yoObject.id // "12312312333645"
Get all properties of the fields object:
Object.keys(yoObject.profile.fields) // ['number-of-fields', 'inside', 'type', 'values']
Get all values of the properies from above:
fields = yoObject.profile.fields
Object.keys(fields).map(key => console.log(fields[key])) // ["700", ["test1", "test2"], "test", "450"] // Note: Order isn't guaranteed
Just play about with things. Throw the object in the console and start to manually traverse it. Then try to loop over things.
Have fun!
Note: I tested none of that! :P
this is a question in regards on the right way to loop deep in JSON
objects – #user2402107
There's no right way. Sometimes you'll need to be fully dynamic, other times you can hardcode paths into nested properties and values.
Fiddle-Diddle
Nest as many times as you need:
angular.forEach(values, (value, key) => {
console.log("Value for", key, ":", value);
angular.forEach(value, (value, key) => {
console.log("Value for", key, ":", value);
angular.forEach(value, (value, key) => {
console.log("Value for", key, ":", value);
})
})
});
You can log the whole object to console. By using F12 tool, you can browse the object in the browser.
console.log(objectName);
angular.forEach works on arrays. lets suppose you have an array of objects as this
var values = [{
"profile": {
"fields": {
"number-of-fields": "700",
"interpertation": [
"whenever this is ready"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
},
{
"profile": {
"fields": {
"number-of-fields": "700",
"interpertation": [
"whenever this is ready"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
}]
you can explore each object and its properties like this
angular.forEach(values, function(value, key) {
console.log(value.profile.fields.values);
});
you can use . notation to access propertes

JSON string array is always null

I have some JSON data rendered server-side to be available in the client page. In the HTTP response it looks correct:
digitalData = {
"page": {
"pageInfo": {
"geoRegion": "US",
"onsiteSearchResults": 38,
"onsiteSearchTerm": "leather",
"sysEnv": "HAMP"
},
"category": {
"dirID": 2,
"pageTemplate": "/store/search.aspx",
"pageType": "Search"
},
"attributes": {
"searchType": "standard",
"refinementCategory": "10001",
"searchFilters": ["50859"]
}
},
"user": {
"profile": {
"profileInfo": {
"profileID": "{C0A253A9-AD6E-4B6B-A313-3D215704D0FB}",
"returningStatus": "new"
}
},
"segment": {
"persona": ["EXPERT"]
}
},
"cart": {
"cartID": "2508d65f-6495-4256-8125-75767b847e45",
"numItems": 0
},
"version": "1.0"
};
But when I examine the DOM through Dev Tools Elements or Console, the searchFilters string array in the above JSON is always null. I have no client side code that refers to that object at all. How/why is it going from correct in the HTTP Response to null in the DOM? I've validated the JSON in JSONLint and it is valid.
The JSON is valid. Append square brackets and try again.
var objArray= [{
"page": [{
"pageInfo": [{
"geoRegion": "US",
"onsiteSearchResults": 38,
"onsiteSearchTerm": "leather",
"sysEnv": "HAMP"
}],
"category": [{
"dirID": 2,
"pageTemplate": "/store/search.aspx",
"pageType": "Search"
}],
"attributes": [{
"searchType": "standard",
"refinementCategory": "10001",
"searchFilters": ["50859"]
}]
}],
"user": [{
"profile": {
"profileInfo": {
"profileID": "{C0A253A9-AD6E-4B6B-A313-3D215704D0FB}",
"returningStatus": "new"
}
},
"segment": {
"persona": ["EXPERT"]
}
}],
"cart": [{
"cartID": "2508d65f-6495-4256-8125-75767b847e45",
"numItems": 0
}],
"version": "1.0"
}];
function getDetails(){
document.getElementById("demo").innerHTML = "Length of Array = " + objArray.length;
document.getElementById("element").innerHTML = "0th Element of Array = " + objArray[0];
document.getElementById("elementInfo").innerHTML = "Element at 0th position Array = " + objArray[0].page[0].pageInfo;
document.getElementById("elementInfo2").innerHTML = "Element at 00th position Array = " + objArray[0].page[0].pageInfo[0].geoRegion;
}
<button onclick=getDetails()> Check </button>
<p id="demo"></p>
<p id="element"></p>
<p id="elementInfo"></p>
<p id="elementInfo2"></p>

Resources