在Javascript中将Array对象转换为Json

时间:2016-04-11 14:17:00

标签: javascript arrays json

我该如何转换:

var expenseList = [[1,"Beverages"],
                   [2,"Condiments" ],
                    [3,"Confections" ],
                   [4,"Dairy Products" ],
                   [5,"Grains/Cereals" ],
                   [6,"Meat/Poultry" ],
                    [7,"Produce" ],
                   [8,"Seafood" ]];

进入这个:

output = [
               { value: 1, text: "Beverages" },
               { value: 2, text: "Condiments" },
               { value: 3, text: "Confections" },
               { value: 4, text: "Dairy Products" },
               { value: 5, text: "Grains/Cereals" },
               { value: 6, text: "Meat/Poultry" },
               { value: 7, text: "Produce" },
               { value: 8, text: "Seafood" }
        ];

第一个数据源可以作为输入,第二个是所需的输出。 我尝试使用循环将数组转换为一种字符串,然后将字符串解析为json,但Json.pasre在那里抛出错误。

var list = '';
for (var i = 0; i < expenseList.length; i++) {
        var showText = expenseList[i][1].replace('"', '\\"');
        var key = expenseList[i][0];

    list = '{ value: ' + key + ', text: "' + value + '"},' + list;
}

    list = '[' + list.substr(0, list.length - 1) + ']';
    var bindList;
    bindList = JSON.parse(list);

4 个答案:

答案 0 :(得分:7)

只需尝试

var output = expenseList.map(function(val){
  return { value: val[0], text: val[1] }
}); 

答案 1 :(得分:1)

您可以使用Array.prototype.map

var list = expenseList.map(function(x) {
  return {
     value: x[0],
     text: x[1]
  };
});

然后转为JSON,你可以使用

var json = JSON.stringify(output);

答案 2 :(得分:0)

这是一种替代解决方案,它以您尝试的方式构建阵列,但更正确:

var expenseList = [[1,"Beverages"],
                   [2,"Condiments" ],
                   [3,"Confections" ],
                   [4,"Dairy Products" ],
                   [5,"Grains/Cereals" ],
                   [6,"Meat/Poultry" ],
                   [7,"Produce" ],
                   [8,"Seafood" ]];

var list = [];
for (var i = 0; i < expenseList.length; i++) {
    var val = expenseList[i][0];    
    var txt = expenseList[i][1];

    list.push({value: val, text: txt});
}

console.log(list);

答案 3 :(得分:0)

如果您不希望数组和哈希对象满足您的要求,请使用它。

使用了loadash。

_.zipObject(_.map(expenseList,0),_.map(expenseList,1))

输出

{1: "Beverages", 2: "Condiments", 3: "Confections", 4: "Dairy Products", 5: "Grains/Cereals", 6: "Meat/Poultry", 7: "Produce", 8: "Seafood"}