我有一个多维数组,如下所示:
products = '[["A","Apple","20","apple.html"],["B","Banana","13","banana.html"],["C","Cereal","45","cereal.html"],["D","Dishes","320","dishes.html"]]';
我试图将其转换为JSON对象(至少我认为格式是什么),但只有索引1和3 ......所以产品[0] [1],产品[0] [3]。这就是我的结果需要看起来的样子。
pList = [{value: 'Apple', data: 'apple.html'},{value: 'Banana', data: 'banana.html'}];
如何完成这项工作?
答案 0 :(得分:3)
按JSON.parse
将字符串解析为数组。
使用Array.prototype.map()从数组中获取值。
var products = '[["A","Apple","20","apple.html"],["B","Banana","13","banana.html"],["C","Cereal","45","cereal.html"],["D","Dishes","320","dishes.html"]]';
products = JSON.parse(products);
var pList = products.map(function(item) {
return {
value: item[1],
data: item[3]
};
});
console.log(pList);