javascript - 从嵌套在对象属性中的数组中提取数据
问题描述
我试图从我的数组中获取一些数据,但我似乎总是在与数组作斗争。我的数据采用以下结构
{
tempAttachments: [{
_id: "12345-678910",
bytes: 412051,
file: 'File',
size: 411532,
title: "someFile.csv",
headers: ['optionOne', undefined, 'optionTwo', undefined, undefined, 'optionThree'],
type: "file",
fileType: "typeOne"
}, {
_id: "9999-2222",
bytes: 12345,
file: 'File',
size: 23456,
title: "anotherFile.csv",
headers: ['optionOne'],
type: "file",
fileType: "typeTwo"
}
]
}
我正在尝试将标题部分放入自己的数组中。索引很重要,因为它们与某些东西有关。我也使用 fileType 作为标识符。所以我的目标是最终得到这样的东西
[
{
"typeOne": [
"optionOne",
"optionTwo",
"optionThree"
]
},
{
"typeTwo": [
"optionOne"
]
}
]
如您所见,我忽略了未定义的选项。所以我目前正在尝试的是这个
const mapping = {}
for (const attachment of this.tempAttachments) {
for (const [index, header] of attachment.headers.entries() || []) {
mapping[attachment.fileType] = [
index, header
]
}
}
不幸的是,结果如下
[
{
"typeOne": [
0,
"optionOne"
]
},
{
"typeTwo": [
0,
"optionOne"
]
}
]
那么我怎样才能实现我所追求的输出呢?
谢谢
解决方案
您可以使用Array.prototype.map()
withArray.prototype.filter()
来摆脱undefind
's inside header
:
const src = {tempAttachments:[{_id:"12345-678910",bytes:412051,file:'File',size:411532,title:"someFile.csv",headers:['optionOne',undefined,'optionTwo',undefined,undefined,'optionThree'],type:"file",fileType:"typeOne"},{_id:"9999-2222",bytes:12345,file:'File',size:23456,title:"anotherFile.csv",headers:['optionOne'],type:"file",fileType:"typeTwo"}]},
result = src
.tempAttachments
.map(({headers,fileType}) => ({
[fileType]: headers.filter(Boolean)
}))
console.log(result)
.as-console-wrapper{min-height:100%;}
推荐阅读
- google-cloud-functions - GCP Console:console.log() 跨越多行
- python - 如何解决传递依赖冲突问题?
- reactjs - 如何在 ReactJS 中将模板文字转换为 html?
- c - 在 C 代码的后面部分丢弃 volatile 限定符
- python - 编码参数是否适用于 pandas.read_excel?
- node.js - 如何在 MongoDB 模式中使用数组类型(使用 Mongoose),使得数组由另一个表的 _id 组成
- ios - React Native iOS - 如何将配置文件添加到提交到 Appstore 的 ipa
- node.js - Discord.js 删除 X 消息
- python - 带有外部连接 SQL SERVER 的 Django 2.2
- python - Discord.py:如何修复“事件循环已关闭”