我有以下JSON响应

    {
        "ProductDetails": [
            {
              "id": "1234",
              "description": "Testing Product1",
              "name": "Product1",
              "displayName": "Product1",
              "favourite": true,
              "iconURL": "testNadIconURL",
              "productType": "Application"
            },
            {
              "id": "8754",
              "name": "ProductFroGroup",
              "displayName": "ProductFroGroup",
              "favourite": false,
              "productType": "Application"
            },
            {
              "id": "8546",
              "applicationURL": "http://example.com",
              "description": "Test description",
              "name": "ASO",
              "displayName": "Product3",
              "favourite": false,
              "iconURL": "http://example/ux/images/phone-icon.png",
              "productType": "Application"
            }
        ]
    }


JS

$ctrl.appList = response.data.ProductDetails;
    for (var i = 0; i <= $ctrl.appList.length; i++) {
        if ($ctrl.appList[i].iconURL != undefined) {
            var valid = /^(ftp|http|https):\/\/[^ "]+$/.test($ctrl.appList[i].iconURL);
            if (valid) {
                console.log("URL avaibale");
                } else {
                $ctrl.appList[i].iconURL.push("http://example/ux/images/phone-icon.png");
                }
        } else {
            $ctrl.appList[i].iconURL.push("http://example/ux/images/phone-icon.png");
        }
}


我在尝试着


如果iconURL为null,则将iconURL设置为默认URL值。
如果iconURL在响应中不可用,则将iconURL设置为相同的默认URL。


我想将键和值对都推到数组的每个对象。

最佳答案

您可以通过以下方式解决它:

var regExp = /^(ftp|http|https):\/\/[^ "]+$/;
var appList = response.data.ProductDetails;
appList.forEach(function(app) {
    var iconURL = app.iconURL || "";
    if (!iconURL || !regExp.test(iconURL)) {
        app.iconURL = "http://example/ux/images/phone-icon.png";
    }
});
$ctrl.appList = appList;

09-07 12:45