首页 > 解决方案 > 如何使用 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"
}

]

标签: javascriptmultidimensional-arrayforeachfunctional-programmingreduce

解决方案


使用Array.mapArray.reduceObject.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);


推荐阅读