javascript - 访问唯一的嵌套 JSON 数组项

标签 javascript json

我正在尝试深入研究以下数组,以便在解析后将所有连接器类型项转换为选择选项。

目前,我可以获得我需要的所有数据,但我想将返回的每个项目转换为单个字符串,而不是让它返回具有多个连接器类型的项目作为单个项目(在下面示例显示了我当前拥有/想要的东西。那并且只显示唯一类型,因此如果连接器名称已显示一次,则不要再次显示该名称作为选项。

例如(当前输出):

(显示重复项,不止一种类型的嵌套项不会分行)

ConnectorType1
ConnectorType1, ConnectorType2, ConnectorType3
ConnectorType1
ConnectorType1, ConnectorType2

期望的输出:

(仅显示唯一项,所有结果都换行)

ConnectorType1,
ConnectorType2,
ConnectorType3

带有 JSON 示例的 Pastebin:

{
    "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
        }
    ]
}

循环遍历 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>`);
          }
        }

最佳答案

我建议您使用 Array.from(myJson.ChargeDevice[0].Connector, ... 遍历所有连接。

然后对于每个连接,您将 .ConnectorType 的值push 到一个数组 (myConnArr) 中(如果它不存在)。像这样 if(!myConnArr.includes(conn.ConnectorType)) myConnArr.push(conn.ConnectorType)

最后,我join所有结果并像这样将它们分开.join(",\n")

完整的代码片段。出于测试目的,我复制了一些连接器值以显示 remove_duplicates() 工作正常。

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

关于javascript - 访问唯一的嵌套 JSON 数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53308841/

相关文章:

javascript - JSON 响应未根据 SQL 查询正确排序

jquery - JavaScript 中的 GroupBy 用于对 JSON 数据进行分组并填充到 optgroup 上

javascript - 如何在 Angular Fire 中保存对象的属性而不删除其他属性?

javascript - 谷歌图表注释未显示

javascript - 减少 Highcharts 中的 x 轴标签密度

javascript - Trello API - 将卡片与板连接以根据板 ID 获取板名称

javascript - 将 Json 对象导出到文本文件

javascript - 清除时的 JQuery UI 组合框事件

javascript - 仅在监听器函数中加载脚本/模块会导致问题吗?

c# - 具有复杂类型参数的 WebInvoke 不适用于 Json 端点