javascript - 从数组中提取数据到它自己的数组中
问题描述
我在数组中有以下数据。
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
}
})
我不确定的是如何映射选项的索引,并将键设置为它们的名称(如果存在)。实现这一目标的最佳方法是什么?
谢谢
解决方案
一种干净的方法是使用该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;
})
推荐阅读
- java - why am I receiving stale element reference on test method?
- angular - 找不到模块“./sc-modal/sc-modal.module”
- sql - 最后一天的数据 向客户发送了一封提醒信
- azure - 由于找不到 GOOGLE_APPLICATION_CREDENTIALS 文件,Google Cloud Vision 反向图像搜索在 Azure 应用服务上失败
- javascript - 如何在单击表格中的按钮时添加动态行?
- uwp - 将带有文本描述的约会添加到日历视图
- elasticsearch - ElasticSearch 波斯语分词
- unity3d - unity Scaling rect 左右变换并缩放 x
- javascript - 乘法时数值显示不正确
- bash - 超时执行持续时间而不是命令