首页 > 解决方案 > 从数组中提取数据到它自己的数组中

问题描述

我在数组中有以下数据。

tempAttachments:Array[2]
  0:Object
    _id:"12345-678910"
    bytes:412051
    file:File
    size:411532
    title:"someFile.csv"
    headers: Array[3]
        0: optionOne
        1: undefined
        2: optionTwo
        3: undefined
        4: undefined
        5: optionThree
    type:"file"
    fileType:"typeOne"
  1:Object
    _id:"9999-2222"
    bytes:12345
    file:File
    size:23456
    title:"anotherFile.csv"
    headers: Array[3]
        0: optionOne
    type:"file"
    fileType:"typeTwo"

我对两个元素感兴趣,那就是 _id 和 headers 数组。我试图结束这样的事情

Array
(
  [0] => Array
  (
     [id] => 12345-678910
     [optionOne] => 0
     [optionTwo] => 2
     [optionThree] => 5
  )
  [1] => Array
  (
     [id] => 9999-2222
     [optionOne] => 0
  )
)

所以本质上,这三个选项的 id 和索引与它们在文件中的列相关。问题是,一个文件最多可以有三个选项(使用上面的名称),但是它们可能只有一个或两个。

所以我就这样开始了

const payload = {}

this.tempAttachments.forEach(function (attachment, index) {
  payload[index] = {
    id: attachment._id
  }
})

我不确定的是如何映射选项的索引,并将键设置为它们的名称(如果存在)。实现这一目标的最佳方法是什么?

谢谢

标签: javascriptarraysdata-structuresmappingreduce

解决方案


一种干净的方法是使用该Array.map方法,它从另一个数组创建一个新数组。

(更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map )

下面的代码将转换tempAttachments为新格式,其中基于此结构:

[
  {
    id: AttachmentID
    optionName: optionIndex
    optionName: optionIndex
    ...
  }
]

它只会添加具有值的选项,而忽略undefined选项。

解决方案:

const payload = tempAttachments.map(attachment => {
  const newAttachment = {
    id: attachment._id,
  }

  attachment.headers.forEach((option, index) => {
    if (option) {
      newAttachment[option] = index;
    }
  })

  return newAttachment;
})

推荐阅读