我需要获取JSON响应的内部内容

时间:2017-09-11 08:19:51

标签: javascript angularjs json spring

我有以下代码从服务器检索JSON响应,它运行正常。

Javascript代码:

$http({
    method: 'POST',
    url: 'http://***SOMEURL',
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json'},
    data: JSON.stringify(data)   
})
.then(function (response) {
    $scope.myData = response.data;
    $scope.myData1=response.data.message.connectionDetailses;
});

响应是

{
    "code": 100,
    "message": {
        "id": 29020,
        "customerCode": "730",
        "name": "John P. M.    168",
        "lastName": "X",
        "houseName": "Hosuseahjkahsh",
        "address1": "1",
        "address2": "x",
        "address3": "wehwhkjwh P. O.",
        "postalCode": "686011",
        "email": "11@11.com",
        "phone": "1234567890",
        "mobile": "1234567890",
        "operatorName": "abcd ",
        "connectionDetailses": [
            {
                "customerCode": "730",
                "accountId": 5,
                "dueAmount": 0,
                "connectionId": 27203,
                "accountName": "M S"
            },
            {
                "customerCode": "730",
                "accountId": 5,
                "dueAmount": 2000,
                "connectionId": 116303,
                "accountName": "MS"
            },
            {
                "customerCode": "730",
                "accountId": 9,
                "dueAmount": 0,
                "connectionId": 116303,
                "accountName": "Connection"
            },
            {
                "customerCode": "730",
                "accountId": 14,
                "dueAmount": 0,
                "connectionId": 116303,
                "accountName": "Amc"
            }
        ]
    }
}

我需要根据connectionId打印连接详细信息。我能够一次打印所有连接细节。但我需要在一个区块内打印细节。

{
                "customerCode": "730",
                "accountId": 9,
                "dueAmount": 0,
                "connectionId": 116303,
                "accountName": "Connection"
}

2 个答案:

答案 0 :(得分:1)

给定connectionId,您可以通过以下方式打印相应的连接细节:

let connectionId = 116303
let connectionDetail = response.data.message.connectionDetailses.find(det => det.connectionId === connectionId);
console.log(connectionDetail);

如果您想要根据相同的ID获取所有详细信息,可以使用array.filter:

let connectionId = 116303
let connectionDetails = response.data.message.connectionDetailses.filter(det => det.connectionId === connectionId);
console.log(connectionDetails);

答案 1 :(得分:0)

我想,您可以使用Array#filter仅过滤具有所需ID的连接。类似的东西:

const details = response.data.message.connectionDetailses
  .filter(connection => connection.connectionId === 116303)[0]