在angularjs中使用逗号(,)将json数据作为字符串获取

时间:2017-02-08 13:31:46

标签: angularjs json ionic-framework

我从服务器获取JSON数据如下: -

"skills": [
        {
            "957": "Modules",
            "958": "Sales and Distribution",
            "959": "Material Management",
            "960": "Finance",
            "961": "Controlling",
            "963": "Human Resource"
        }
    ],

我需要将数据打印为:

技能组合="模块,销售和分销,物料管理,财务,控制,人力资源"

我尝试但没有成功。

$scope.skillset = JSON.stringify($scope.skills);

5 个答案:

答案 0 :(得分:2)

首先,您必须解析json对象并选择已解析数组的第一个元素。然后进行转换以获得所需的字符串。

var obj = angular.fromJson($scope.skills)[0];
    //ES6
    var skillset = Object.keys(obj).map((key) => {
       return obj[key]
    }).join(',');

   //ES5
   var skillset = Object.keys(obj).map(function(key) {
       return obj[key]
    }).join(',');

这是一个有效的plunker

答案 1 :(得分:2)

var skills= [
        {
            "957": "Modules",
            "958": "Sales and Distribution",
            "959": "Material Management",
            "960": "Finance",
            "961": "Controlling",
            "963": "Human Resource"
        }
    ];

var valueArray = Object.values(skills[0]);
console.log(valueArray.toString());

答案 2 :(得分:1)

您可以使用Object.values()来获取JSON的值。

var skillValues = Object.values($scope.skills[0]);
$scope.skillset = skillValues.join();

答案 3 :(得分:0)

使用简单的javascript for ...

$http.get("your_json_data").then(
    function (res) {

        var skills = res.data.skills;
        var aux,
            aux2 = "";

        for (var i = 0; i < skills.length; i++) {
            aux = skills[i];
            for (k in aux) {
                if(aux.hasOwnProperty(k)){
                    aux2 += aux[k] + ",";
                }
            }
        }

        $scope.viewData = "skills=\"" + aux2.substring(0, aux2.length - 1) + "\"";
           //$scope.viewData is ready to be shown on the view
    }
)

答案 4 :(得分:0)

你需要一个键值循环来处理这个问题。

var response = {
    "skills": [{
        "957": "Modules",
        "958": "Sales and Distribution",
        "959": "Material Management",
        "960": "Finance",
        "961": "Controlling",
        "963": "Human Resource"
    }]
}

var skills = response.skills[0];
var skillset = "";

for (var key in skills) {
    skillset += skills[key] + ', ';
}

console.log(skillset);