如何使用json数组获取表达式

时间:2015-08-01 08:58:38

标签: javascript jquery arrays json

我的json数组看起来像: -

Array 1 = [{"label":"1"},{"value":"6412"},{"label":"1"},{"value":"6413"},{"label":"2"},{"value":"6417"},{"label":"3"},{"value":"6418"},{"label":"3"},{"value":"6419"}];

现在我希望结果如下: -

result = ["#1|6412,6413","#2|6417","#3|6418,6419"];

3 个答案:

答案 0 :(得分:0)

这样可行,当然我强烈建议你改变你的json结构。

var arr = [{"label":"1"},{"value":"6412"},{"label":"1"},{"value":"6413"},{"label":"2"},{"value":"6417"},{"label":"3"},{"value":"6418"},{"label":"3"},{"value":"6419"}];

var formatted = [];

for (i=0;i<arr.length;i+=2)
{
    var label = "#" + arr[i].label;
    var value =arr[i+1].value
    if (formatted[label] == null) 
        formatted[label] = value;
    else               
        formatted[label] += ", " +value;
}

console.log(formatted);

编辑:现在它返回一个数组:[#1: "6412, 6413", #2: "6417", #3: "6418, 6419"]

https://jsfiddle.net/4zr0q8j3/

答案 1 :(得分:0)

Array arr有你的答案

*男人改变你的问题需要付出双倍的努力

<html>
    <head>
        <script>
        //var json = '{"0":"1","1":"2","2":"3","3":"4"}';
        // result = ["#1|6412,6413#2|6417#3|6418,6419"];
        var json = '[{"label":"1"},{"value":"6412"},{"label":"1"},{"value":"6413"},{"label":"2"},{"value":"6417"},{"label":"3"},{"value":"6418"},{"label":"3"},{"value":"6419"}]';

        var parsed = JSON.parse(json);
        var rahul='';
        var rahul_old;
        var arr = [];

        for(var x in parsed){
        //  alert(parsed[x]);

            for(var x2 in parsed[x]){

                if(x2=='label'){
                        if(parseInt(rahul_old)==parseInt(parsed[x][x2])){
                            rahul+=",";

                        }else{
                            if(rahul.trim()!=''){
                            //  alert(rahul);
                                arr.push(rahul);
                                rahul='';
                            }

                            rahul+=("#"+parsed[x][x2]+"|");
                        }
                    rahul_old=parseInt(parsed[x][x2]);
                }else if(x2=='value'){
                    rahul+=parsed[x][x2];

                }
            }


        }
        if(rahul.trim()!=''){
                                alert(rahul);
                            //  arr.push(rahul);
                                rahul='';
                            }
                            //arr have you result
                            alert(arr.length);



        </script>
    </head>
    <body>

    </body>
</html>

答案 2 :(得分:-1)

更改您的json格式如下:

var array = [
{
    "label": "1",
    "value": [
        6412,
        6413
    ]
},
{
    "label": "2",
    "value": [
        6417
    ]
},
{
    "label": "3",
    "value": [
        6418,
        6419
    ]
}
];

var result = [];
for(i in array){

  var temp = "#"+array[i].label+"|"+array[i].value.join();
  result.push(temp);

}
console.log(result);  // output is ["#1|6412,6413", "#2|6417", "#3|6418,6419"]