将多维数组的内容转储到新的JSON变量中

时间:2015-08-03 17:54:17

标签: javascript jquery arrays json multidimensional-array

我有一个多维数组,如下所示:

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'}];

如何完成这项工作?

1 个答案:

答案 0 :(得分:3)

  1. JSON.parse将字符串解析为数组。

  2. 使用Array.prototype.map()从数组中获取值。

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