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

标签 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...所以 products[0][1],products[0][3 ]。这就是我的结果需要的样子。

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

我该如何完成这项工作?

最佳答案

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

关于javascript - 将多维数组的内容转储到新的 JSON 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31793684/

相关文章:

javascript - AngularJs unicode 选择 fontawesome

javascript - jquery 输入元素取消选择文本事件?

在纯 C 的数组中选择具有更多重复项的元素

javascript - 使用 goog.bind 和 goog.net.Xhrio.send 了解 "this"上下文

javascript - 使用动态绑定(bind)数据检测文本区域的变化?

javascript - 简单的 jQuery 不会加载

javascript - 从数组中删除所有某些重复项

java - Tic Tac Toe 游戏 - 数组没有保存值(value)?

javascript - datePicker 仅在双击时显示

jquery - 向带进度条的 jquery slider 添加暂停、下一个和上一个按钮