【问题标题】:Push key value to the json array in Javascript在Javascript中将键值推送到json数组
【发布时间】:2017-02-09 10:54:42
【问题描述】:

我的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。

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

【问题讨论】:

  • 好的。到目前为止,您为实现这一目标做了什么尝试?
  • 另外,简化问题中的代码会更容易回答。
  • 尝试用iconURL = "url"替换iconURL.push("url")

标签: javascript angularjs arrays json push


【解决方案1】:

你可以这样解决:

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;

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多