Sha
Sha

Reputation: 1974

Push key value to the json array in Javascript

I have the json response as follows

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

I am trying to

  1. To set the iconURL to a default url value if the iconURL is null.
  2. Set the iconURL to the same default url if the iconURL is not available in the response.

I want to push both the key and value pair to each object of the array.

Upvotes: 0

Views: 516

Answers (1)

Artem Bozhko
Artem Bozhko

Reputation: 1854

You can solve it in this way:

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;

Upvotes: 1

Related Questions