【问题标题】:Dumping the contents of a multi-dimension array into a new JSON variable将多维数组的内容转储到新的 JSON 变量中
【发布时间】:2015-08-03 17:54:16
【问题描述】:

我有一个看起来像这样的多维数组:

products = '[["A","Apple","20","apple.html"],["B","Banana","13","banana.html"],["C","Cereal","45","cereal.html"],["D","Dishes","320","dishes.html"]]';

我正在尝试将其转换为 JSON 对象(至少我认为格式是这样的),但只有索引 1 和 3... 所以 products[0][1],products[0][3 ]。这就是我的结果需要的样子。

pList = [{value: 'Apple', data: 'apple.html'},{value: 'Banana', data: 'banana.html'}];

我该如何完成这项工作?

【问题讨论】:

    标签: javascript jquery arrays json multidimensional-array


    【解决方案1】:
    1. 通过JSON.parse将字符串解析为数组。

    2. 使用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);

    【讨论】:

    • 太棒了!!!只是想知道......我正在寻找 JSON 的 pList 格式吗?
    • 不,它只是一个具有这些值的数组,如果需要,可以使用plist = JSON.stringify(plist) 将其转换为 JSON。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2018-10-30
    • 2017-05-16
    • 2021-05-04
    • 2021-03-27
    • 1970-01-01
    相关资源
    最近更新 更多