将键值推送到 Javascript 中的 json 数组

Push key value to the json array in Javascript

我有如下 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");
        }
}

我正在尝试

  1. 如果 iconURL 为空,则将 iconURL 设置为默认 url 值。
  2. 如果 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;