Loop through a JSON object to map column name and value - javascript

below is my JSON
{
"portfolioID": 3024,
"gridType": "OWNER",
"gridLayoutId": 4,
"totalRecordCount": 111,
"attributeMetaData": [
{
"attributeId": 94,
"attributeName": "OWNERTYPE",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 0,
"sortType": "",
"attributeDisplayName": "TYPE",
"columnOrder": 1,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "false",
"isActionable": "",
"actionType": "",
"referenceAttribute": "",
"attributeDataType": "STRING",
"columnWidth": "",
"isFreezable": ""
},
{
"attributeId": 95,
"attributeName": "OWNERSTATUS",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 0,
"sortType": "",
"attributeDisplayName": "STATUS",
"columnOrder": 2,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "false",
"isActionable": "",
"actionType": "",
"referenceAttribute": "",
"attributeDataType": "STRING",
"columnWidth": "",
"isFreezable": ""
},
{
"attributeId": 93,
"attributeName": "PREFERREDNAME",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 1,
"sortType": "ASC",
"attributeDisplayName": "LICENSE OWNER NAME",
"columnOrder": 3,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "false",
"isActionable": "true",
"actionType": "VIEWPAGE",
"referenceAttribute": "LICENSEOWNERID",
"attributeDataType": "STRING",
"columnWidth": "",
"isFreezable": ""
},
{
"attributeId": 115,
"attributeName": "LICENSEOWNERID",
"objectType": "OWNER",
"filterValue1": "",
"filterValue2": "",
"filterOperator1": "",
"filterOperator2": "",
"columnSortOrder": 0,
"sortType": "",
"attributeDisplayName": "LICENSEOWNERID",
"columnOrder": 0,
"isGeneralAttribute": "true",
"isIndustryAttribute": "",
"isCustomerAttribute": "",
"dataSource": "Pega",
"isHidden": "true",
"isActionable": "",
"actionType": "",
"referenceAttribute": "",
"attributeDataType": "INTEGER",
"columnWidth": "",
"isFreezable": ""
}
],
"attributeValues": [
{
"objectId": 133218,
"attributeList": [
{
"attributeId": 94,
"attributeValue": "Entity",
"referenceObjectId": null
},
{
"attributeId": 95,
"attributeValue": "Active",
"referenceObjectId": null
},
{
"attributeId": 93,
"attributeValue": null,
"referenceObjectId": "133218"
},
{
"attributeId": 115,
"attributeValue": "133218",
"referenceObjectId": null
}
]
},
{
"objectId": 134179,
"attributeList": [
{
"attributeId": 94,
"attributeValue": "Individual",
"referenceObjectId": null
},
{
"attributeId": 95,
"attributeValue": "Active",
"referenceObjectId": null
},
{
"attributeId": 93,
"attributeValue": "Ra vi Teja",
"referenceObjectId": "134179"
},
{
"attributeId": 115,
"attributeValue": "134179",
"referenceObjectId": null
}
]
}
]
}
Tried below JS
data.attributeValues.forEach((item, i) => {
const itemattrId = item.attributeList[i].attributeId;
data.attributeMetaData.forEach((subItem, j) => {
const subitemattrId = subItem.attributeId;
if (itemattrId === subitemattrId) {
console.log(subItem.attributeName + ' - ' + item.attributeList[i].attributeValue);
}
});
});
I want to loop through this JSON to get the mapping of column name and column values. In the JSON the mapping is done by the property called 'attributeId'. in 'attributeMetaData', 'attributeName' is the name of the column and in 'attributeValues', there is multiple 'attributeList' and in each of them have the 'attributeId' and 'attributeValue' properties. Actually I am trying to build an object to proper name value pairs to bind it to a grid. So, based on 'attributeId', I wanted to map each name value pairs. Any help would be greatly appreciated. Thanks.

const idToNameMap = {};
obj.attributeMetaData.forEach(item => {
idToNameMap[item.attributeId] = item;
})
const rows = obj.attributeValues.map(attributeObj => {
const row = { objectId: attributeObj.objectId };
attributeObj.attributeList.forEach(attr => {
if (idToNameMap[attr.attributeId].isHidden !== "true") {
row[idToNameMap[attr.attributeId].attributeName] = attr.attributeValue;
}
});
return row;
});
console.log(rows); //Prints:
//[
// {
// objectId: 133218,
// OWNERTYPE: 'Entity',
// OWNERSTATUS: 'Active',
// PREFERREDNAME: null,
// },
// {
// objectId: 134179,
// OWNERTYPE: 'Individual',
// OWNERSTATUS: 'Active',
// PREFERREDNAME: 'Ra vi Teja',
// }
//]

Related

How to Parse nested Json In Java script

I have this json in js,
and i am trying to get the key from the "Data" Object, like the SessionId and Email.
Please Help...
{
"HasError": false,
"Errors": [],
"ObjectName": "WebCheckoutCreateSessionResponse",
"Data": {
"HasError": false,
"ReturnCode": 0,
"ReturnMessage": null,
"SessionId": "abcde",
"SessionUrl": "https://pci.aaa.com/WebCheckout/Angular/Checkout.html#!/ZCreditWebCheckout/55cf7d1306b2bcc15d791dde524d2b4f616421172e6d75a013597c8dd2668843",
"RequestData": {
"Key": "ad",
"Local": "He",
"UniqueId": "<InvNo>1705</InvNo><InvYear>3102</InvYear><SugMismah>15</SugMismah><key>ad</key>",
"SuccessUrl": "",
"CancelUrl": "",
"CallbackUrl": "",
"PaymentType": "regular",
"CreateInvoice": false,
"AdditionalText": "",
"ShowCart": true,
"ThemeColor": "005ebb",
"Installments": {
"Type": "regular",
"MinQuantity": 1,
"MaxQuantity": 12
},
"Customer": {
"Email": "someone#gmail.com",
"Name": "Demo Client",
"PhoneNumber": "077-3233190",
"Attributes": {
"HolderId": "none",
"Name": "required",
"PhoneNumber": "required",
"Email": "optional"
}
},
"CartItems": [
{
"Amount": 117,
"Currency": "US",
"Name": "Danny ",
"Description": "Hi ",
"Quantity": 1,
"Image": "https://www.aaa.com/site/wp-content/themes/z-credit/img/decisions/decision2.png",
"IsTaxFree": false
}
],
"GetCurrencyCode": "376",
"BitButtonEnabled": true,
"MaxPayButtonEnabled": true,
"ApplePayButtonEnabled": true,
"GooglePayButtonEnabled": true,
"ShowTotalSumInPayButton": true
}
},
"ResponseType": 0
}
const population = JSON.parse(xhr.responseText);
for (const key in population) {
if (population.hasOwnProperty(key)) {
console.log(`${key}: ${population[key]}`);
}
}
You forgot to index the Data property.
const population = JSON.parse(xhr.responseText).Data;
for (const key in population) {
console.log(`${key}: ${population[key]}`);
}

Looping through nested JSON returns NULL

I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?

Incorrect output when using lodash on results returned by mongoose

I have a result set returned from a mongodb query and am using lodash to reformat it. I am trying to convert the array of objects into a single object. The problem is when I use lodash on the result set, I get unexpected output.
NOTE: Running the snippet on codepen/codesandbox gives correct output, but not when used directly from mongoose results.
Mongoose Query
try {
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
});
if(!petInfo) {
return res.status(400).json({ message: "FAILED_TO_FETCH_PET_INFO" });
}
let newObj = _.reduce(petInfo, (acc, cur)=> { return _.assign(acc, cur) }, {});
return res.status(200).json(newObj);
}
catch (error) {
req.errorMsg = error.message; // Log actual error
return res.status(500).json({ message: "SOME_ERROR_OCCURRED" });
}
Result from mongoose find query (petInfo)
[
{
"age": {
"days": "",
"months": "",
"years": ""
},
"userId": "45422605180207851194",
"name": "Oscar",
"gender": "FEMALE",
"type": "Dog",
"breed": "",
"weight": "",
"spayOrNeuter": false,
"petId": "KSVv7yJLnUWX3n"
}
]
Lodash snippet
let newObj = _.reduce(petInfo, (acc, cur)=> { return _.assign(acc, cur) }, {});
return res.status(200).json(newObj);
Result after modification
{
"$__": {
"strictMode": true,
"selected": {
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
},
"getters": {
"age": {
"days": "",
"months": "",
"years": ""
}
},
"wasPopulated": false,
"scope": {
"age": {
"days": "",
"months": "",
"years": ""
},
"userId": "45422605180207851194",
"name": "Oscar",
"gender": "FEMALE",
"type": "Dog",
"breed": "",
"weight": "",
"spayOrNeuter": false,
"petId": "KSVv7yJLnUWX3n"
},
"activePaths": {
"paths": {
"userId": "init",
"petId": "init",
"name": "init",
"gender": "init",
"type": "init",
"breed": "init",
"age.days": "init",
"age.months": "init",
"age.years": "init",
"weight": "init",
"spayOrNeuter": "init"
},
"states": {
"ignore": {},
"default": {},
"init": {
"userId": true,
"name": true,
"gender": true,
"type": true,
"breed": true,
"age.days": true,
"age.months": true,
"age.years": true,
"weight": true,
"spayOrNeuter": true,
"petId": true
},
"modify": {},
"require": {}
},
"stateNames": [
"require",
"modify",
"init",
"default",
"ignore"
]
},
"pathsToScopes": {},
"cachedRequired": {},
"session": null,
"$setCalled": {},
"emitter": {
"_events": {},
"_eventsCount": 0,
"_maxListeners": 0
},
"$options": {
"skipId": true,
"isNew": false,
"willInit": true
},
"nestedPath": "age"
},
"isNew": false,
"_doc": {
"age": {
"days": "",
"months": "",
"years": ""
},
"userId": "45422605180207851194",
"name": "Oscar",
"gender": "FEMALE",
"type": "Dog",
"breed": "",
"weight": "",
"spayOrNeuter": false,
"petId": "KSVv7yJLnUWX3n"
},
"$locals": {},
"$init": true
}
The reason for this is because mongoose doesn't return the object you think it does. Instead, it returns a 'mongoose' object with a bunch of methods ect ect. There are 2 ways around this, either call .lean() on your query or toJSON() on the result to sanitize result into normal js object.
.lean()
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
}).lean();
.toJSON()
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
}).lean();
const parsed = petInfo.toJSON()
Your query will return the result set as document objects instead of plain objects, which is why you get all the additional information like strictMode, getters, etc.
You could use the lean() function in order to get plain objects only (see https://mongoosejs.com/docs/tutorials/lean.html), e.g.:
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
}).lean();

best way to loop over Json in Javascript

SO I have this setting json
[{
"name": "Business",
"skip": "0",
"pos": "1"
},
{
"name": "contact",
"skip": "1",
"pos": "3"
},
{
"name": "UKSite",
"skip": "0",
"pos": "2"
}
]
Then I have my data json
[{
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Sri",
"con_fName": "Jhon",
"con_lName": "Snow",
"emails": ["maheshwar#hsjsk.com", ""],
"phones": ["8867116216", ""]
},
"repeatable": false
}, {
"name": "UKAddress",
"hideShow": true,
"data": {
"addAddress": [{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}, {
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}]
},
"repeatable": false
}, {
"name": "Business",
"hideShow": true,
"data": {
"biss_name": "Nano Corporation"
},
"repeatable": false
}, {
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Mr",
"con_fName": "Roshan",
"con_lName": "Aslam",
"emails": ["roshan#throughbit.com"],
"phones": ["8867116216"]
},
"repeatable": true
}, {
"name": "UKSite",
"hideShow": true,
"data": {
"site_name": "naonocrporation.co.uk",
"external_rff": "fsfsfs",
"con_title": "Mr",
"con_fName": "Kash",
"con_lName": "Sangh",
"emails": ["kash#youremail.com"],
"phones": ["8867116216"],
"addAddress": [{
"add_bilding_num": "",
"add_street_name": "",
"add_town": "",
"add_county": "",
"add_pc": "",
"add_type": ""
}],
"ElecMeter": [{
"distrib_id": "DISTRIBUTOR ID",
"pc": "PROFILE CLASS",
"mtc": "METER TIMESWITCH CODE",
"llf": "LINE LOSS FACTOR",
"mpc": "MPAN CORE",
"eac": "EAC",
"c_supplr": "CURRENT SUPPLIER",
"c_date": "CURRENT END DATE",
"select": true
}, {
"distrib_id": "",
"pc": "",
"mtc": "",
"llf": "",
"mpc": "",
"eac": "",
"c_supplr": "",
"c_date": ""
}],
"GasMeter": [{
"mprn": "MPRN",
"aq": "AQ",
"g_c_supplr": "CURRENT SUPPLIER",
"g_c_date": "CURRENT END DATE"
}]
},
"repeatable": true
}]
I have to loop on the data json and using the information from setting json need to create a new Json
for example
my new json should look like this
[{
"name": "Business",
"hideShow": true,
"data": {
"biss_name": "Nano Corporation"
},
"repeatable": false
},
{
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Mr",
"con_fName": "Roshan",
"con_lName": "Aslam",
"emails": [
"roshan#throughbit.com"
],
"phones": [
"8867116216"
]
},
"repeatable": true
},
{
"name": "UKAddress",
"hideShow": true,
"data": {
"addAddress": [{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
},
{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}
]
},
"repeatable": false
}
]
You can Observe , The term skip:1 which means skip the first one and add rest also the terminology pos:1 which is telling what should be the position of the object in the new array.
Any help would be great
Update 1
I came up with this snippet
ar finalArray = []
for(var i = 0; i < b.length; i++){
var counter = 0;
for(var j = 0; j < a.length; j++){
if(b[i].name == a[j].name){
if(counter < b[i].skip){
counter++;
continue;
}
finalArray.push(a[j])
}
}
}
Thanks
As you are dealing with an array of objects and you want to modify each one during the iteration based on conditions, I'd recommend you to use forEach
You have docs and examples here:
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/map

Find all occurrences of JSON element using jQuery

How can you parse out all the values for a particular data point within a complex json response form a rest service call?
Here is my JQUERY code to get the rest service json response. I am looking to get all occurrences of "Id" for all "Approver" elements found in the json data and add them to delimited list - preferably using a
;
to separate each "Id"
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'MySite/Change/Request/12345/Approvals/GetApprovalGroupUsers?changeNumber=98765',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.Id
}));
});
}
});
});
});
</script>
</head>
<body>
<button>Click me to get listing of Id's</button>
</body>
</html>
The json data from the service in such:
{
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}
This is how you can get all ID's of the approvers, delimited by a semi-colon.
var data = {
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}
data.PossibleApprovers.forEach(function (approver) { document.write(approver.Approver.Id + ';')})

Categories

Resources