I am creating project using nodejs and angularjs. I have json like:
[{
"links": [{
"description": null,
"latency": "1",
"linkid": "26149e91-f6c8-47fb-a10d-691e76486871",
"contracts": null,
"tag": null,
"connections": [
"ce00ba7c-4916-4920-a7dc-7b70daea9e7a",
"6d3ec325-4b27-4772-b0d9-36d4cc7b9e47"
],
"type": "0",
"linkStatus": 1,
"bandwitdth": 799999
}, {
"description": null,
"latency": "1",
"linkid": "2f11f857-251f-4b01-9140-12abfda8d79b",
"contracts": null,
"tag": null,
"connections": [
"bcdc3622-f0b3-4bf2-80fd-3aaee5af1c4c",
"ca059990-937e-4b29-8a21-615244d56689"
],
"type": "0",
"linkStatus": 1,
"bandwitdth": 1024
}, {
"description": null,
"latency": "1",
"linkid": "7cf69528-13bc-4b90-b952-549fbbab1032",
"contracts": null,
"tag": null,
"connections": [
"b164c679-f9d9-406d-94a8-b85b99a03bdc",
"616e4bce-592e-4864-b9f6-149f541fc7d1"
],
"type": "0",
"linkStatus": 1,
"bandwitdth": 1024
}, {
"description": null,
"latency": "1",
"linkid": "d6b67215-6ca5-4f63-8573-e952c132d4af",
"contracts": null,
"tag": null,
"connections": [
"ebe0a008-29d2-48f9-bd71-4324a0712618",
"bc36697a-4768-46a1-8e05-62376103b476"
],
"type": "0",
"linkStatus": 1,
"bandwitdth": 1024
}, {
"description": "TestFlow",
"latency": "1",
"linkid": "fd73608aa8e7b440",
"contracts": null,
"tag": null,
"connections": [
"49b33cd1-5722-4e8e-b40c-03c3407c5efe",
"cd354769-d52a-414e-bb7c-f0e0690ddf3b"
],
"type": "0",
"linkStatus": 6,
"bandwitdth": 0
}],
"billing-uuid": "5f1dd7c5-c48b-44ed-be14-cf2a8730fe27"
}]
I need connections in other json. It should be like:
[{
"conn":"49b33cd1-5722-4e8e-b40c-03c3407c5efe"
},
{
"conn":"49b33cd1-5722-4e8e-b40c-03c3407c5efe"
}]
}
My code is like:
var billinData = [];
var connections = [];
for(i = 0; i < body.length; i++){
billingData.push({"billing-account-uuid":body[i]['billing-uuid']})
var nLinksLen = body[i].links.length;
for (j = 0; j < nLinksLen; j++){
var nConLen = body[i].links[j].connections.length
console.log(nConLen)
for (k = 0; k < nConLen; k++){
connections.push({"vportuuid": body[i].links[j].connections[k]});
}
}
}
I am getting this with thousand of records with some of duplicates:
[
{
"conn": "ce00ba7c-4916-4920-a7dc-7b70daea9e7a"
},
{
"conn": "6d3ec325-4b27-4772-b0d9-36d4cc7b9e47"
}]
This does not give correct result.
I just want to know that my loop is correct?
You can use the forEach or reduce Array methods to solve this easily:
var obj= JSON.parse(...);
var connections=obj.links.reduce(function (array,elem) {
elem.connections.forEach(function (conn) {
array.push({'conn': conn});
}
return array;
},[]);
Related
I'm trying to filter the 2nd level of array and if it is true will get the 1st level array in JSON data. I'm using jQuery grep to find the specific element of an array and to filter the department and the jobs.title.
In my case I'm trying to search job title "FULL" and the data is under the department of Marketing. So I'm trying to achieve that if the data "FULL" exist under Marketing Department then Display Marketing Department Jobs.
For JSON file I'm using greenhouse API for testing.
{
"departments": [
{
"id": 4009377006,
"name": "Client Success",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009378006,
"name": "Creative",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009379006,
"name": "Engineering",
"parent_id": null,
"child_ids": [],
"jobs": [
{
"absolute_url": "https://boards.greenhouse.io/frequence/jobs/4044313006",
"data_compliance": [
{
"type": "gdpr",
"requires_consent": false,
"retention_period": null
}
],
"internal_job_id": 4034527006,
"location": {
"name": "Menlo Park, CA"
},
"metadata": [
{
"id": 4410278006,
"name": "Desired Timezones",
"value": [],
"value_type": "multi_select"
}
],
"id": 4044313006,
"updated_at": "2023-02-02T13:40:43-05:00",
"requisition_id": "TEST101",
"title": "TEST HIRING - SOFTWARE ENGINEER"
}
]
},
{
"id": 4009380006,
"name": "Finance",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009381006,
"name": "Marketing",
"parent_id": null,
"child_ids": [],
"jobs": [
{
"absolute_url": "https://boards.greenhouse.io/frequence/jobs/4044533006",
"data_compliance": [
{
"type": "gdpr",
"requires_consent": false,
"retention_period": null
}
],
"internal_job_id": 4034679006,
"location": {
"name": "Menlo Park, CA, or New York City, NY, or Washington DC"
},
"metadata": [
{
"id": 4410278006,
"name": "Desired Timezones",
"value": [],
"value_type": "multi_select"
}
],
"id": 4044533006,
"updated_at": "2023-02-02T13:40:43-05:00",
"requisition_id": "TEST103",
"title": "TEST HIRING - FULL STACK DEVELOPER"
},
{
"absolute_url": "https://boards.greenhouse.io/frequence/jobs/4044315006",
"data_compliance": [
{
"type": "gdpr",
"requires_consent": false,
"retention_period": null
}
],
"internal_job_id": 4034529006,
"location": {
"name": "Menlo Park, CA, or New York City, NY, or Washington DC"
},
"metadata": [
{
"id": 4410278006,
"name": "Desired Timezones",
"value": [],
"value_type": "multi_select"
}
],
"id": 4044315006,
"updated_at": "2023-02-02T13:40:43-05:00",
"requisition_id": "TEST102",
"title": "TEST HIRING - PHP DEVELOPER"
}
]
},
{
"id": 4009382006,
"name": "Operations",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009383006,
"name": "People",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009384006,
"name": "Product",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009385006,
"name": "Sales",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 0,
"name": "No Department",
"parent_id": null,
"child_ids": [],
"jobs": []
}
]
}
This is what I've been working below.
$.getJSON('https://boards-api.greenhouse.io/v1/boards/frequence/departments/',
function(data) {
var search_term = 'FULL';
var search = search_term.toUpperCase();
var getDepartment = '';
var filterDept = $.grep(data.departments, function (element, index) {
var search_filter = element.name.toUpperCase().indexOf(search) >= 0;
console.log(element);
if(search_filter <= 0){
// I'm trying to achieve here is to check if the element exist in 2nd level of array
//and if true it will retrieve the parent array or 1st level of array.
filterDept = $.grep(element.jobs, function (element1, index1) {
search_filter = element1.title.toUpperCase().indexOf(search) >= 0;
if(search_filter == true) {
search_filter = element.name.toUpperCase().indexOf(search) >= 0;
console.log(element1.title);
return false;
}
});
}
return search_filter;
});
console.log(filterDept);
});
Here is the way I would approach this:
const search_term = 'FULL';
const search = search_term.toUpperCase();
// Use helpful names like "department" and "job" instead of
// "element" and "element1" - this improves readability.
const matches = $.grep(data.departments, function (department) {
const isMatch = department.name.toUpperCase().indexOf(search) >= 0;
// Return `true` early if we have a direct name match.
if (isMatch) { return true; }
// If we haven't matched directly on name, we will filter
// the department's jobs for matches.
const jobMatches = $.grep(department.jobs, function (job) {
return job.title.toUpperCase().indexOf(search) >= 0;
});
// We consider this department to be a match if its filtered
// jobs has any elements (ie., its `.length` is greater than 0).
return jobMatches.length > 0;
});
I have created a fiddle for reference.
Update
I feel I should add that I used jQuery's grep function in my example only because it was mentioned in the question.
I would not use jQuery for this functionality because modern JavaScript has the methods on the Array prototype to do the filtering we require.
Here is an example in plain JavaScript:
const search_term = 'FULL';
const search = search_term.toUpperCase();
const matches = data.departments.filter(department => {
const isMatch = department.name.toUpperCase().indexOf(search) >= 0;
return isMatch || department.jobs.some(job => job.title.toUpperCase().indexOf(search) >= 0);
});
And here is a fiddle that uses this code.
I have 3 arrays as below
A: [
{
"label": "100Watts",
"value": "100Watts",
},
{
"label": "135Watts",
"value": "135Watts",
} ]
B: [
{
"label": "Large|100cm",
"value": "Large|100cm"
},
{
"label": "Small|125mm",
"value": "Small|125mm"
}
]
C: [
{
"label": "Black",
"value": "Black",
},
{
"label": "Black",
"value": "Black",
}
]
I have one master array as below
result:[
{
"x_powerConsumption": "100Watts",
"x_size": "Small|125mm",
"x_color": "Black",
},
{
"x_powerConsumption": "135Watts",
"x_size": "Large|100cm",
"x_color": "Black",
}
]
My code as below
let newArray = A.filter(o1 => result.some(o2 => o1.label === o2.x_size));
let newArray2 = B.filter(o1 => result.some(o2 => o1.label === o2.x_powerConsumption));
this.setState({selectedVarientOne: newArray[0].label, selectedVarientTwo:newArray2[0].label})
But my requirement is i need combination as below like
Output : Black --> 100Watts --> Small|125mm
But as per my above code it is coming like
Black --> 100Watts --> Large|100mm
Can anyone tell me how i can solve this?
Ok, I'm assuming that you want to match the array of objects to the main object
I just use a nest of for loops to see if values from an array(A,B, or C) match up with values from the main object(result) from only the important keys in the result object of course
var A=[{"label":"100Watts","value":"100Watts"},{"label":"135Watts","value":"135Watts"}]
var B=[{"label":"Large|100cm","value":"Large|100cm"},{"label":"Small|125mm","value":"Small|125mm"}]
//now for function to correlate data(sry for late answer was afk lol)
function attribute(arr,result){
const necessary_keys=["x_powerConsumption","x_size","x_color"]
var toReturn=[] //array with output to return
for(let i=0;i<arr.length;i++){
var arrValues=Object.values(arr[i]) //eg: A[0] would be ["100Watts","100Watts"]
for(let j=0;j<result.length;j++){
var resultValues=Object.keys(result[j])
.filter(key=>necessary_keys.includes(key))
.map(key=>result[j][key]) //result[0] would be ["100Watts","Small|125mm","Black"]
if(resultValues.some(value=>arrValues.includes(value))){
toReturn[i]=resultValues //["100Watts","Small|125mm","Black"] for arr[0]
}
}
}
return toReturn //all indexes with undefined dont correlate with result in any of its values
}
//now to use the function
let newArray=attribute(A,result)
let newArray2=attribute(B,result)
console.log("values from A:",newArray)
console.log("values from B:",newArray2)
<script>
var result=[
{
"dynamicPropertyMapLong": {
"sku-Equipment_x_color": 1,
"sku-Equipment_x_size": 1,
"sku-Equipment_x_powerConsumption": 3
},
"x_UAE_installationPrice": 0,
"bundleLinks": [],
"largeImage": null,
"smallImage": null,
"listVolumePrice": null,
"onlineOnly": false,
"listPrices": {
"aed": 100,
"loyaltyProgram": null
},
"configurationMetadata": [],
"largeImageURLs": [],
"x_skuCreationDate": null,
"productLine": null,
"listVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"derivedSalePriceFrom": "aed",
"model": null,
"x_powerConsumption": "100Watts",
"barcode": null,
"salePriceEndDate": null,
"images": [],
"unitOfMeasure": null,
"primaryMediumImageURL": null,
"dynamicPropertyMapBigString": {},
"active": true,
"x_promotionDetails": "5 Percent Off: 5OFF5",
"thumbImageURLs": [],
"mediumImageURLs": [],
"primarySourceImageURL": null,
"x_description": null,
"sourceImageURLs": [],
"primarySmallImageURL": null,
"x_autoShipPrice": 0,
"productFamily": null,
"primaryThumbImageURL": null,
"nonreturnable": false,
"x_loyaltyLevel": "LEVEL2",
"displayName": "Three variant sku1",
"salePrices": {
"aed": null,
"loyaltyProgram": null
},
"primaryFullImageURL": null,
"productListingSku": null,
"primaryLargeImageURL": null,
"derivedOnlineOnly": false,
"smallImageURLs": [],
"thumbnailImage": null,
"saleVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"x_size": "Small|125mm",
"saleVolumePrice": null,
"salePriceStartDate": null,
"quantity": null,
"salePrice": null,
"fullImageURLs": [],
"x_isonSale": "Y",
"variantValuesOrder": {},
"x_color": "Black",
"soldAsPackage": true,
"listingSKUId": null,
"x_SAR_installationPrice": 0,
"repositoryId": "300003-1",
"derivedListPriceFrom": "aed",
"x_installationPrice": 0,
"x_costPrice": null,
"configurable": false,
"listPrice": 100
},
{
"dynamicPropertyMapLong": {
"sku-Equipment_x_color": 1,
"sku-Equipment_x_size": 2,
"sku-Equipment_x_powerConsumption": 1
},
"x_UAE_installationPrice": 0,
"bundleLinks": [],
"largeImage": null,
"smallImage": null,
"listVolumePrice": null,
"onlineOnly": false,
"listPrices": {
"aed": 135,
"loyaltyProgram": null
},
"configurationMetadata": [],
"largeImageURLs": [],
"x_skuCreationDate": null,
"productLine": null,
"listVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"derivedSalePriceFrom": "aed",
"model": null,
"x_powerConsumption": "135Watts",
"barcode": null,
"salePriceEndDate": null,
"images": [],
"unitOfMeasure": null,
"primaryMediumImageURL": null,
"dynamicPropertyMapBigString": {},
"active": true,
"x_promotionDetails": "5 Percent Off: 5OFF5",
"thumbImageURLs": [],
"mediumImageURLs": [],
"primarySourceImageURL": null,
"x_description": null,
"sourceImageURLs": [],
"primarySmallImageURL": null,
"x_autoShipPrice": 0,
"productFamily": null,
"primaryThumbImageURL": null,
"nonreturnable": false,
"x_loyaltyLevel": "LEVEL2",
"displayName": "sku3",
"salePrices": {
"aed": null,
"loyaltyProgram": null
},
"primaryFullImageURL": null,
"productListingSku": null,
"primaryLargeImageURL": null,
"derivedOnlineOnly": false,
"smallImageURLs": [],
"thumbnailImage": null,
"saleVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"x_size": "Large|100cm",
"saleVolumePrice": null,
"salePriceStartDate": null,
"quantity": null,
"salePrice": null,
"fullImageURLs": [],
"x_isonSale": "Y",
"variantValuesOrder": {},
"x_color": "Black",
"soldAsPackage": true,
"listingSKUId": null,
"x_SAR_installationPrice": 0,
"repositoryId": "300003-3",
"derivedListPriceFrom": "aed",
"x_installationPrice": 0,
"x_costPrice": null,
"configurable": false,
"listPrice": 135
}
]
</script>
Assuming the other answer is correct, here is a shorter version:
result.map(({x_powerConsumption, x_size, x_color}) => ([
A.find(el => el.label === x_powerConsumption).value,
B.find(el => el.label === x_size).value,
C.find(el => el.label === x_color).value
]))
Example:
const A = [{ "label": "100Watts", "value": "100Watts" }, { "label": "135Watts", "value": "135Watts" }];
const B = [{ "label": "Large|100cm", "value": "Large|100cm" }, { "label": "Small|125mm", "value": "Small|125mm" }];
const C = [{ "label": "Black", "value": "Black" }, { "label": "Black", "value": "Black" }];
const result = [
{ "x_powerConsumption": "100Watts", "x_size": "Small|125mm", "x_color": "Black" },
{ "x_powerConsumption": "135Watts", "x_size": "Large|100cm", "x_color": "Black" }
];
console.log(result.map(({x_powerConsumption, x_size, x_color}) => ([
A.find(el => el.label === x_powerConsumption).value,
B.find(el => el.label === x_size).value,
C.find(el => el.label === x_color).value
])));
I want to get the latest timeStamp and userID from the json response for which the actualDataArray.status =="Approved" ,for populating it on the template
{
"dataArray": [
{
"Id": 11,
"Name": "HJ Enterprises",
"Code": "HJC",
"description": "HJ APProved",
"Status": "OK",
"actualDataArray": [
{
"timeStamp": "2019-05-07-06.26.23.991068",
"status": "Approved",
"userID": "#23444",
"articles": ""
},
{
"timeStamp": "2019-05-07-06.37.27.978668",
"status": "Rejected",
"userID": "#1234",
"articles": "articles"
},
{
"timeStamp": "2019-05-08-06.26.28.991068",
"status": "Approved",
"userID": "#1233e",
"articles": ""
},
],
},
expected output should be the latest timeStamp and userId corresponding to that timestamp.
Please help me with this.
With this you can get the latest object with Approved status.
const data = {
"dataArray": [
{
"Id": 11,
"Name": "HJ Enterprises",
"Code": "HJC",
"description": "HJ APProved",
"Status": "OK",
"actualDataArray": [
{
"timeStamp": "2019-05-07-06.26.23.991068",
"status": "Approved",
"userID": "#23444",
"articles": ""
},
{
"timeStamp": "2019-05-07-06.37.27.978668",
"status": "Rejected",
"userID": "#1234",
"articles": "articles"
},
{
"timeStamp": "2019-05-08-06.26.28.991068",
"status": "Approved",
"userID": "#1233e",
"articles": ""
},
],
}
]
}
let dataArr = data.dataArray
dataArr.forEach((dataPoint, i) => {
let actualDataArray = dataPoint.actualDataArray
let sortedActualDataArray = actualDataArray.sort((a, b) => {
(new Date(a.timeStamp) > new Date(b.timeStamp)) ? 1 : -1
})
let timeStampElem = undefined
if(dataPoint.status != "Ok"){
timeStampElem = tempSearchArr[0]
}
else {
timeStampElem = tempSearchArr[1]
}
console.log(timeStampElem)
console.log(`TimeStamp: ${timeStampElem.timeStamp}`)
console.log(`UserID: ${timeStampElem.userID}`)
})
Try this code:
var jsonObj = {
"dataArray": [
{
"Id": 11,
"Name": "HJ Enterprises",
"Code": "HJC",
"description": "HJ APProved",
"Status": "OK",
"actualDataArray": [
{
"timeStamp": "2019-05-07-06.26.23.991068",
"status": "Approved",
"userID": "#23444",
"articles": ""
},
{
"timeStamp": "2019-05-07-06.37.27.978668",
"status": "Rejected",
"userID": "#1234",
"articles": "articles"
},
{
"timeStamp": "2019-05-08-06.26.28.991068",
"status": "Approved",
"userID": "#1233e",
"articles": ""
},
],
}
]
};
var approvedUsers = {};
var totalData = jsonObj.dataArray.length;
var i = 0;
while(i < totalData) {
var actualsData = jsonObj.dataArray[i].actualDataArray;
var actualLength = actualsData.length;
var j = 0;
while(j < actualLength) {
if (actualsData[j].status === "Approved") {
approvedUsers[actualsData[j].userID] = actualsData[j];
}
j += 1;
}
i += 1;
}
console.log(approvedUsers);
In this, I am aggregating the data with "Approved" status in a separate var and at the end showing it in a console.log(). You may use this var as per your need.
In the ui, I have created a custom transaction search with vendor lines. How do I access vendor lines values? I have something like this:
var veResults = vendorSearch.run().getRange({
start: 0,
end: 50
});
for(var i = 0; i < veResults.length; i++)
{
var vendorName = veResults[i].getValue({name: 'vendorLine.entityid');
context.response.write(vendorName);
};
If I print veResults, I get the following json:
[
{
"recordType": "vendorpayment",
"id": "210",
"values": {
"employee.entityid": "",
"trandate": "5/20/2015",
"print": "Print",
"type": [
{
"value": "VendPymt",
"text": "Bill Payment"
}
],
"payrollbatch": "",
"tranid": "2009",
"entity": [
{
"value": "35",
"text": "Pacific Bell Telephone"
}
],
"account": [
{
"value": "1",
"text": "1000 Checking"
}
],
"otherrefnum": "",
"statusref": [],
"trackingnumbers": "",
"memo": "",
"currency": [
{
"value": "1",
"text": "USA"
}
],
"expectedreceiptdate": "",
"trandate_1": "5/20/2015",
"enddate": "",
"item": [],
"vendorLine.entityid": "Pacific Bell Telephone",
"vendorLine.billaddress": "Pacific Bell Telephone\nPacific Bell Payment Center\nSacramento CA 95887-0001\nUS"
}
...]
So, the value is there, how do I get it? The search object has only getValue and getText methods, none of which work in this case.
There is a syntax error with this line
var vendorName = veResults[i].getValue({'vendorLine.entityid');
It should be
var vendorName = veResults[i].getValue('vendorLine.entityid');
Kindly help me in sorting the below JSON list in the controller and display in the view.
Actually orderBy filter sorting one level, But I need it sort even for childs recursively.
Input:
R2
-->S4
------>T5
------>T4
-->S3
R1
-->S2
------>T2
------>T1
-->S1
Output:
R1
-->S1
------>T1
------>T2
-->S2
R2
-->S3
------>T4
------>T5
-->S4
Please find the sample in Plunker.
http://plnkr.co/edit/JslHwJ1CBREKf6FgYHaZ?p=preview
var sortNames = function(arr){
arr = arr.sort(function(a,b){
return a.name > b.name;
})
for (var i = 0; i < arr.length; i++){
if (arr[i].childs){
sortNames(arr[i].childs)
}
}
return arr;
}
var names = [
{
"name": "Root1",
"Id": "2f3d17cb-d9e2-4e99-882d-546767f2765d",
"status": "",
"dispName": "",
"imageURL": "",
"childCount": "",
"childs": [
{
"name": "Sub1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f98f",
"childs": [
{
"name": "Template1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981",
"status": "",
"dispName": "",
"imageURL": ""
},
{
"name": "Template2",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f982",
"status": "",
"dispName": "",
"imageURL": ""
}
]
},
{
"name": "Template3",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981"
}
]
},
{
"name": "Root2",
"Id": "ea0586e7-02cf-4359-94ba-8d9623590dfe",
"childs": [
{
"name": "Sub2",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c9",
"childs": [
{
"name": "Template4",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c1"
},
{
"name": "Template5",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c2"
}
]
}
]
}
];
sortNames(names);