Order of Array Elements Causing Error - javascript

I have two arrays. Elements of each array are shown as below:
allLabBranches = [{
"labbranchid": "1",
"labname": "Wahab Labs, Islampura Branch, Lahore",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHB",
"address": "56 Islampura, Lahore",
"landlineno": "04237940445",
"datecreated": "2016-03-11 11:00:00",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-05-04 00:53:03",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-05-04"
}, {
"labbranchid": "2",
"labname": "Wahab Labs, Model Town Branch, Lahore",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHAB",
"address": "45 Model Town, Lahore",
"landlineno": "04237945485",
"datecreated": "2016-03-11 11:00:00",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "0000-00-00"
}, {
"labbranchid": "3",
"labname": "Shahdara More Branch",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHAB",
"address": "Shahdara",
"landlineno": "04237933415",
"datecreated": "2016-03-11 11:48:15",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "0000-00-00"
}, {
"labbranchid": "4",
"labname": "New Branch",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHB",
"address": "More Samanabad, Lahore",
"landlineno": "042361561",
"datecreated": "2016-03-11 11:52:06",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-03-14 15:06:44",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-14"
}, {
"labbranchid": "5",
"labname": "Test Branch",
"labtitle": "xyz",
"shortname": "sfwe",
"address": "dsfasd",
"landlineno": "sdfasd",
"datecreated": "2016-03-12 00:14:11",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-08-11 12:54:12",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-12"
}, {
"labbranchid": "6",
"labname": "Test Branch 2",
"labtitle": "asdfs",
"shortname": "asdfs",
"address": "asdf",
"landlineno": "asdf",
"datecreated": "2016-03-12 12:16:24",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-12"
}, {
"labbranchid": "7",
"labname": "Wahab Labs, Shahdara Branch, Lahore",
"labtitle": "Shahdara",
"shortname": "Shahdara",
"address": "Shahdara",
"landlineno": "0423744915",
"datecreated": "2016-08-11 12:56:27",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-08-11 12:57:01",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-08-01"
}]
Another array elements are:
labsOfUser = [{
"userhasbranchid": "53",
"labbranches_labbranchid": "6",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "54",
"labbranches_labbranchid": "1",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "55",
"labbranches_labbranchid": "7",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "56",
"labbranches_labbranchid": "2",
"usersoflabs_userId": "9"
}]
Now I have a Select Multiple Box and I show some branches as selected and some as not selected. The code is given below:
function populateSelectedLabs() {
$('#labbranchids').empty();
if (allLabBranches.length >= labsOfUser.length) {
for (var i = 0; i < allLabBranches.length; i++) {
for (var j = 0; j < labsOfUser.length; j++) {
if (allLabBranches[i].labbranchid == labsOfUser[j].labbranches_labbranchid) {
$("#labbranchids").append("<option selected='selected' value='" + allLabBranches[i].labbranchid + "'>" + allLabBranches[i].labname + "</option>");
allLabBranches = jQuery.grep(allLabBranches, function(value) {
return value != allLabBranches[i];
});
} //end inner if
} //end inner loop
} //end outer loop
} //end if
for (var i = 0; i < allLabBranches.length; i++) {
$("#labbranchids").append("<option value='" + allLabBranches[i].labbranchid + "'>" + allLabBranches[i].labname + "</option>");
} //end for loop
} //end function
The problem is that array element comparison misses an element which is present in the array but located at different index in the array. The error occurs at following line of code:
if(allLabBranches[i].labbranchid == labsOfUser[j].labbranches_labbranchid){
Kindly help me to know how to compare all the elements in both array?

The reason why certain items are not matched is that you redefine the allLabBranches inside the loop on that same array, making it shorter.
Let's assume that before that change the following is true:
labsOfUser[j-1].labbranches_labbranchid == allLabBranches[i+1].labbranchid
You would expect this equality to be detected later, in the next iteration of the outer loop. But because of the re-assignment to allLabBranches, this value no longer is at index i+1, but at i. This value will no longer be matched during the remaining part of the inner loop (because the matching value is at j-1), and so i will increment for the next iteration of the outer loop. As a consequence this value will never be matched.
You could solve this by iterating backwards through the allLabBranches array, but even better would be to create a hash with the values from the labsOfUser array. This will have better performance.
You can do that like this:
function populateSelectedLabs() {
$('#labbranchids').empty();
// create hash
var hash = {};
for (var j = 0; j < labsOfUser.length; j++) {
hash[labsOfUser[j].labbranches_labbranchid] = 1;
}
allLabBranches = jQuery.grep(allLabBranches, function(value) {
return hash[value.labbranchid];
}).concat(jQuery.grep(allLabBranches, function(value) {
return !hash[value.labbranchid];
}));
for (var i = 0; i < allLabBranches.length; i++) {
$("#labbranchids").append($('<option>')
.val(allLabBranches[i].labbranchid)
.text(allLabBranches[i].labname)
.attr('selected', hash[allLabBranches[i].labbranchid]));
}
}
If the target browsers support ES6, then you could write it like this:
function populateSelectedLabs() {
$('#labbranchids').empty();
var hash = new Set(labsOfUser.map( value => value.labbranches_labbranchid ));
allLabBranches.filter( value => hash.has(value.labbranchid) )
.concat(allLabBranches.filter( value => !hash.has(value.labbranchid) ))
.forEach( value =>
$("#labbranchids").append($('<option>')
.val(value.labbranchid)
.text(value.labname)
.attr('selected', hash.has(value.labbranchid)))
);
}

Related

JS Recursive Nested JSON Array Children Join Key

[
{
"PRODUCT_CATEGORY_ID": "1",
"NAME": "OTOMOBİL PARÇALARI",
"DESCRIPTION": "Araba Parçaları",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "",
"children": [
{
"PRODUCT_CATEGORY_ID": "3",
"NAME": "HONDA PARÇALARI",
"DESCRIPTION": "Honda Parçaları",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "1"
},
{
"PRODUCT_CATEGORY_ID": "4",
"NAME": "RENAULT PARÇALARI",
"DESCRIPTION": "Renault Parçaları",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "1",
"children": [
{
"PRODUCT_CATEGORY_ID": "5",
"NAME": "MINIMAL RENAULT PARÇALARI",
"DESCRIPTION": "",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "4"
}
]
}
]
}
]
I have a json with nested children and I want the paths of this object's children. nested children can be even more.I want as output is a string array.
[
"OTOMOBİL PARÇALARI"
"OTOMOBİL PARÇALARI > HONDA PARÇALARI"
"OTOMOBİL PARÇALARI > RENAULT PARÇALARI"
"OTOMOBİL PARÇALARI > RENAULT PARÇALARI > MINIMAL RENAULT PARÇALARI"
]
I tried
function findAllChildren (id, results, depth) {
for (d in data) {
if (data[d].parent == id) {
data[d].depth = depth
results.push(data[d])
findAllChildren(data[d].id, results, depth + 1)
}
}
}
var results = []
findAllChildren(1, results, 0)
return results.map(function (element) { return Array(element.depth + 1).join(' -> ') + element.name})
Thank you for your help in advance, I searched and couldn't find it, you can share it with me in the link.
You can use a a recursive approach, say, creating a function getPaths that will get a list of paths using a property key as an input.
In this case we'll use 'NAME', and build up an array of the relevant paths.
let input = [ { "PRODUCT_CATEGORY_ID": "1", "NAME": "OTOMOBİL PARÇALARI", "DESCRIPTION": "Araba Parçaları", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "", "children": [ { "PRODUCT_CATEGORY_ID": "3", "NAME": "HONDA PARÇALARI", "DESCRIPTION": "Honda Parçaları", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "1" }, { "PRODUCT_CATEGORY_ID": "4", "NAME": "RENAULT PARÇALARI", "DESCRIPTION": "Renault Parçaları", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "1", "children": [ { "PRODUCT_CATEGORY_ID": "5", "NAME": "MINIMAL RENAULT PARÇALARI", "DESCRIPTION": "", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "4" } ] } ] } ]
function getPaths(obj, property, path = '') {
const paths = [];
for(let k in obj) {
if (typeof(obj[k]) === 'object') {
paths.push(...getPaths(obj[k], property, path));
} else if (k === property) {
path += (path ? ' > ' : '') + obj[k];
paths.push(path)
}
}
return paths;
}
console.log('Paths:', getPaths(input, 'NAME'))

Accessing unique nested JSON array items

I'm trying to dig into the following array, to turn all of the connector type items into select options when I have parsed it.
At the moment, I can get all the data I require, but I'm wanting to turn each item returned into a single string as opposed to having it return items that have more than one connector type as a single item (beneath example shows what I currently have / desire. That and only show unique types, so if the connector name has been showed once, don't show that name again as an option.
For example (current output):
(Shows duplicates, nested items with more than one type don't break onto single lines)
ConnectorType1
ConnectorType1, ConnectorType2, ConnectorType3
ConnectorType1
ConnectorType1, ConnectorType2
Desired output:
(Shows unique items only, all results broken onto new lines)
ConnectorType1,
ConnectorType2,
ConnectorType3
Pastebin with JSON example:
{
"ChargeDevice": [
{
"ChargeDeviceId": "cfeedcdd5e287bef4b583158a12363f1",
"ChargeDeviceRef": "SRC_LDN60188",
"ChargeDeviceName": "2 Riddons Road",
"ChargeDeviceText": null,
"ChargeDeviceLocation": {
"Latitude": "51.431454",
"Longitude": "0.031175",
"Address": {
"SubBuildingName": null,
"BuildingName": "",
"BuildingNumber": "",
"Thoroughfare": "Riddons Road",
"Street": "Junction with Chinbrook Road",
"DoubleDependantLocality": null,
"DependantLocality": null,
"PostTown": "Leek",
"County": "Greater London",
"PostCode": "SE12 9QR",
"Country": "gb",
"UPRN": null
},
"LocationShortDescription": null,
"LocationLongDescription": ""
},
"ChargeDeviceManufacturer": null,
"ChargeDeviceModel": null,
"PublishStatusID": "1",
"DateCreated": "2014-08-19 05:15:02",
"DateUpdated": "2015-09-02 11:28:16",
"Attribution": "Source London",
"DateDeleted": "n/a",
"Connector": [
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
}
],
"DeviceOwner": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceController": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceAccess": [],
"DeviceNetworks": "Source London",
"ChargeDeviceStatus": "In service",
"PublishStatus": "Published",
"DeviceValidated": "0",
"RecordModerated": "Y",
"RecordLastUpdated": "2015-09-02 11:28:16",
"RecordLastUpdatedBy": "NCR Admin",
"PaymentRequiredFlag": false,
"PaymentDetails": "",
"SubscriptionRequiredFlag": true,
"SubscriptionDetails": "\u00a35 per annum for RFiD card",
"ParkingFeesFlag": false,
"ParkingFeesDetails": "",
"ParkingFeesUrl": null,
"AccessRestrictionFlag": false,
"AccessRestrictionDetails": "",
"PhysicalRestrictionFlag": false,
"PhysicalRestrictionText": "",
"OnStreetFlag": true,
"LocationType": "On-street",
"Bearing": null,
"Accessible24Hours": false
}
]
}
Current code for looping through JSON:
for (let x = 0; x < data.ChargeDevice[i].Connector.length; x++) {
if (connectors.indexOf(data.ChargeDevice[i].Connector[x].ConnectorType) === -1) {
connectors.push(data.ChargeDevice[i].Connector[x].ConnectorType);
$('#connectorList').append(`<option data-loc-name="${connectors}" value="${connectors}">${connectors}</option>`);
}
}
I would suggest you to loop through all connection with Array.from(myJson.ChargeDevice[0].Connector, ....
Then for each connection, you push the value of .ConnectorType into an array (myConnArr) if it is not already present. Like this if(!myConnArr.includes(conn.ConnectorType)) myConnArr.push(conn.ConnectorType)
Lastly, I join all the result and separate them like this .join(", \n").
The full code snippet. For the test purpose, I duplicate some connector value in order to show remove_duplicates() works fine.
let myJson = {
"ChargeDevice": [
{
"ChargeDeviceId": "cfeedcdd5e287bef4b583158a12363f1",
"ChargeDeviceRef": "SRC_LDN60188",
"ChargeDeviceName": "2 Riddons Road",
"ChargeDeviceText": null,
"ChargeDeviceLocation": {
"Latitude": "51.431454",
"Longitude": "0.031175",
"Address": {
"SubBuildingName": null,
"BuildingName": "",
"BuildingNumber": "",
"Thoroughfare": "Riddons Road",
"Street": "Junction with Chinbrook Road",
"DoubleDependantLocality": null,
"DependantLocality": null,
"PostTown": "Leek",
"County": "Greater London",
"PostCode": "SE12 9QR",
"Country": "gb",
"UPRN": null
},
"LocationShortDescription": null,
"LocationLongDescription": ""
},
"ChargeDeviceManufacturer": null,
"ChargeDeviceModel": null,
"PublishStatusID": "1",
"DateCreated": "2014-08-19 05:15:02",
"DateUpdated": "2015-09-02 11:28:16",
"Attribution": "Source London",
"DateDeleted": "n/a",
"Connector": [
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
}
],
"DeviceOwner": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceController": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceAccess": [],
"DeviceNetworks": "Source London",
"ChargeDeviceStatus": "In service",
"PublishStatus": "Published",
"DeviceValidated": "0",
"RecordModerated": "Y",
"RecordLastUpdated": "2015-09-02 11:28:16",
"RecordLastUpdatedBy": "NCR Admin",
"PaymentRequiredFlag": false,
"PaymentDetails": "",
"SubscriptionRequiredFlag": true,
"SubscriptionDetails": "\u00a35 per annum for RFiD card",
"ParkingFeesFlag": false,
"ParkingFeesDetails": "",
"ParkingFeesUrl": null,
"AccessRestrictionFlag": false,
"AccessRestrictionDetails": "",
"PhysicalRestrictionFlag": false,
"PhysicalRestrictionText": "",
"OnStreetFlag": true,
"LocationType": "On-street",
"Bearing": null,
"Accessible24Hours": false
}
]
};
let myConnArr = [];
Array.from(myJson.ChargeDevice[0].Connector, conn =>
{
if(!myConnArr.includes(conn.ConnectorType)) myConnArr.push(conn.ConnectorType)
});
console.log(myConnArr.join(", \n"));
You could take a Set and check if the item is not in the set, then use the item and add this item to the set.
var array = [{ connector: ['ConnectorType1'] }, { connector: ['ConnectorType1', 'ConnectorType2', 'ConnectorType3'] }, { connector: ['ConnectorType1'] }, { connector: ['ConnectorType1', 'ConnectorType2'] }],
connectors = new Set;
array.forEach(({ connector }) => connector.forEach(c => {
if (connectors.has(c)) return;
console.log(c);
connectors.add(c);
}));
Not sure if this is what you're after, but here is a function that returns an array of the unique connectors within a ChargeDevice and a little test.
function getUniqueConnectors(data) {
var connectors = [];
for (let i in data.ChargeDevice) {
for (let x = 0; x < data.ChargeDevice[i].Connector.length; x++) {
if (connectors.indexOf(data.ChargeDevice[i].Connector[x].ConnectorType) === -1) {
connectors.push(data.ChargeDevice[i].Connector[x].ConnectorType);
}
}
}
return connectors;
}
var objectOne = {
"ChargeDevice": [
{
"ChargeDeviceId": "cfeedcdd5e287bef4b583158a12363f1",
"ChargeDeviceRef": "SRC_LDN60188",
"ChargeDeviceName": "2 Riddons Road",
"ChargeDeviceText": null,
"ChargeDeviceLocation": {
"Latitude": "51.431454",
"Longitude": "0.031175",
"Address": {
"SubBuildingName": null,
"BuildingName": "",
"BuildingNumber": "",
"Thoroughfare": "Riddons Road",
"Street": "Junction with Chinbrook Road",
"DoubleDependantLocality": null,
"DependantLocality": null,
"PostTown": "Leek",
"County": "Greater London",
"PostCode": "SE12 9QR",
"Country": "gb",
"UPRN": null
},
"LocationShortDescription": null,
"LocationLongDescription": ""
},
"ChargeDeviceManufacturer": null,
"ChargeDeviceModel": null,
"PublishStatusID": "1",
"DateCreated": "2014-08-19 05:15:02",
"DateUpdated": "2015-09-02 11:28:16",
"Attribution": "Source London",
"DateDeleted": "n/a",
"Connector": [
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
},
],
"DeviceOwner": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceController": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceAccess": [],
"DeviceNetworks": "Source London",
"ChargeDeviceStatus": "In service",
"PublishStatus": "Published",
"DeviceValidated": "0",
"RecordModerated": "Y",
"RecordLastUpdated": "2015-09-02 11:28:16",
"RecordLastUpdatedBy": "NCR Admin",
"PaymentRequiredFlag": false,
"PaymentDetails": "",
"SubscriptionRequiredFlag": true,
"SubscriptionDetails": "\u00a35 per annum for RFiD card",
"ParkingFeesFlag": false,
"ParkingFeesDetails": "",
"ParkingFeesUrl": null,
"AccessRestrictionFlag": false,
"AccessRestrictionDetails": "",
"PhysicalRestrictionFlag": false,
"PhysicalRestrictionText": "",
"OnStreetFlag": true,
"LocationType": "On-street",
"Bearing": null,
"Accessible24Hours": false
},
]
};
console.log(getUniqueConnectors(objectOne)); //["3-pin Type G (BS1363)", "Type 2 Mennekes (IEC62196)"]

Merging two json array object based on union and intersection

I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.
Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.
I am not sure whether I am using the correct approach. This is what I have try:
var newJsonID = _.pluck(newJson, 'id');
var currentJsonID = _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);
Expected Final Outcome:
[
{
"id": "12",
"property1Name": "1"
"status": "inactive"
},
{
"id": "11",
"property1Name": "1"
"status": "inactive"
},
{
"id": "10",
"property1Name": "1"
"status": "inactive"
},
{
"id": "9",
"property1Name": "1"
"status": "active"
}
]
A solution in plain Javascript with two loops and a hash table for lookup.
function update(newArray, currentArray) {
var hash = Object.create(null);
currentArray.forEach(function (a) {
hash[a.id] = a.status;
});
newArray.forEach(function (a) {
a.status = hash[a.id] || 'inactive';
});
}
var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');

Check if a particular sequence of array elements is empty

["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction","Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"]
I have this array shown above. The first eight elements are the header. So I will remove those using splice.
I need to check if the elements 8,16,24 AND 9,17,25 AND 11,19,27 are empty. How can i loop through this elements dynamically. The sequence of elements are weird. Can someone please suggest how to check if these above element number is the current one which is being looped.
Thanks guys for the replies. I worked on it a bit and the below code worked for me pretty nicely...
var count = 0;
var array2= [0,1,3,4,6];
function checkArray5(cell_data){
for(var i=8;i<cell_data.length; i++) {
for (var j=0;j<5;j++)
{
if (i%8 == array2[j])
{
if(cell_data[i] ==="") {
console.log(count++);
}
}
}
}
}
checkArray5(array);
Use the % operator to search for the indexes that return 0, 1 and 3 respectively:
var table = ["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction","Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"];
var index = 0;
var columns = 8;
var cells = table.slice(columns);
var len = cells.length;
for (;index < len; index++) {
var mod = index % columns;
switch (mod) {
case 0:
case 1:
case 3:
isEmpty(cells[index]);
break;
}
}
Here is my suggestion:
var myArr = ["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction", "Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"];
// added or remove elements to be checked if empty.
var emptyElementChk = [8, 9, 11, 16, 17, 19, 24, 25, 27];
for (var i = 0; i < emptyElementChk.length; i++) {
//All checked array listed
console.log("Key : " + emptyElementChk[i] + " value: " + myArr[emptyElementChk[i]]);
if (myArr[emptyElementChk[i]] == "") {
// empty arrays action
} else {
// none empty arrays action
}
};

accessing a specific set of values from within my json response?

I am trying to use for..in loop to access the description key/value within 'Event' but at the moment am not fully sure how to achieve this. First of all I used the for..in and logged this out, this returns all the top level entries in the response, how do I now drill down and pick out Event.description? I first of all thought it was data[prop].Event.description but thats not the case. Should I be using a normal for loop and then the for..in inside of this?
Here is my current code:
$(document).ready(function() {
var data = {
"status": "ok",
"code": "200",
"message": "event details",
"data": [{
"Event": {
"id": "1",
"name": "Sample Event Number 1",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "1",
"name": "Support #1",
"BandsEvent": {
"id": "7",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "2",
"name": "Support #2",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}},
{
"Event": {
"id": "2",
"name": "Sample Event Number 2",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "2",
"name": "Another Crazy Band",
"BandsEvent": {
"id": "3",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "4",
"name": "The Band",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}}]
}
var prop;
for (prop in data) {
console.log( data[prop] );
// data.Event.description
}
});​
This should do what you want:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description);
}
I should add that the reason that your code doesn't work is that the "prop" variable would first be "status", then "code", then "message" and THEN "data". Status/code/message has no "Event" property, so therefore your code would return undefined if you'd try to access data[prop].Event. Here we pick them out specifically. And since that data.data is an array, there's no reason to use a for .. in loop, but rather just a regular for loop.
Likewise, if you would want to print out the descriptions AND the bands, you could do the following:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description + " has the following bands:");
for (var j = 0; j < data.data[i].Event.Band.length; j++) {
console.log(data.data[i].Event.Band[j].name);
}
}

Categories