在JavaScript中将数组对象转换为Json

3
我该如何转换这个代码:
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.parse会抛出错误。

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);

试图将JSON对象作为字符串构建是非常容易出错的。 - Dan
你所需的输出中没有任何“JSON对象”,或者与JSON相关的任何其他内容。具体而言,有零个。 - Oleg V. Volkov
5个回答

7

简单尝试

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

1
你可以使用 Array.prototype.map
var list = expenseList.map(function(x) {
  return {
     value: x[0],
     text: x[1]
  };
});

然后你可以使用以下代码将其转换为JSON格式:

var json = JSON.stringify(output);

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"}

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);

0
一行解决方案使用.map
var expenseList = [[1,"Beverages"],[2,"Condiments" ],[3,"Confections" ],[4,"Dairy Products" ],[5,"Grains/Cereals" ],[6,"Meat/Poultry" ],[7,"Produce" ],[8,"Seafood" ]],
      output = expenseList.map(([value,text])=>({value:+value,text})); 

console.log(output);

你的答案与其他人有何不同? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接