CrispySinger
CrispySinger

Reputation: 37

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

Upvotes: 1

Views: 79

Answers (3)

Jonathan Gagne
Jonathan Gagne

Reputation: 4379

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

Upvotes: 1

Katie.Sun
Katie.Sun

Reputation: 711

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)"]

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386530

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

Upvotes: 1

Related Questions