首页 > 解决方案 > 从嵌套在对象属性中的数组中提取数据

问题描述

我试图从我的数组中获取一些数据,但我似乎总是在与数组作斗争。我的数据采用以下结构

{
    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"
    ]
  }
]

那么我怎样才能实现我所追求的输出呢?

谢谢

标签: javascriptarraysecmascript-6

解决方案


您可以使用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%;}


推荐阅读