javascript - 如何使用 JavaScript 中的函数式样式将这个数组数组转换为对象数组?
问题描述
对于我试图以特定方式解决的这个问题,我将不胜感激。我正在尝试使用 forEach() 和 reduce() 将数据集从一种格式 - 数组数组 - 转换为另一种格式 - 对象数组。我知道 arr.forEach(i) => {...} 将访问数组中的每个项目,然后我可以使用 arr.reduce(acc, curr) => {...} 来转换嵌套数组及其值到一个对象中,我很难可视化和推理如何在嵌套数组中使用 .reduce() 来访问并因此分配对象中的键值对。提前感谢您的帮助和解释。
这是原始数据:
const theData = [
[
["productName", "The Product"],
["productOrigin", "Some Country"],
["productNumber", 100],
["comment", "Some Comment"]
],
[
["productName", "Another Product"],
["productOrigin", "Some other Country"],
["productNumber", 45],
["comment", "some comment"]
]
]
我正在拍摄的输出是这样的:
const formattedData = [
{
productName: "The Product",
productOrigin: "Some Country",
productNumber: 100,
comment: "Some Comment
},
productName: "Another Product",
productOrigin: "Some other Country",
productNumber: 45,
comment: "Some Comment"
}
]
解决方案
使用Array.map、Array.reduce和Object.assign
使用Array.map,我们可以将数组中的每个条目转换为另一个值。在我们的例子中,我们将一个数组转换为一个对象。
对于每个数组(父数组中的条目),我们将使用Array.reduce,我们将在其中将数组缩减为一个对象。对于数组中的每个条目,我们使用Object.assign在对象中添加键/值对
const theData = [[["productName", "The Product"], ["productOrigin", "Some Country"], ["productNumber", 100], ["comment", "Some Comment"]],[["productName", "Another Product"],["productOrigin", "Some other Country"],["productNumber", 45],["comment", "some comment"]]];
const result = theData.map(v => v.reduce((a,[k,v]) => Object.assign(a, {[k]:v}), {}));
console.log(result);
推荐阅读
- java - 当我尝试在 Apache Tomcat 中上传我的 war 文件时如何解决这个问题?
- java - 我父母的类方法没有收到我的实例变量值
- rust - 如何通过程序宏中的名称获取有关特征的信息?
- snowflake-cloud-data-platform - 是否可以保护雪花中的视图列?
- jquery - 如何使用 css 变换平滑地移动圆圈?
- python - 通过叠加多边形提取像素值
- javascript - 通过js滚动到下一个div
- c - 检查字符串是否为回文
- python - 在同一列上多次调用 Pandas df.sort_values() 会产生不同的结果?
- javascript - 无法将表格附加到 div