javascript - 通过组合两个数组创建一个数组对象
问题描述
https://stackblitz.com/edit/angular-enctgg-dvagm3 问题陈述:我正在尝试将时间从 arr2 修补到 arr1,然后构建整个预期的 o/p,如下所示。
我正在尝试使用地图。但不确定如何遍历嵌套数组。注意:Array1 有嵌套数组,需要将它们映射到 arrar2 代码中:
var result = this.responseValue.map((person, index) => ({ ppmInfoId: { locationCode: person.locationCode, yearMonth: person.locationType, changeOrderId: 20 }, hours: index}));
预期输出:
"ppmInfo": [
{
"ppmInfoId": {
"changeOrderId": 0,
"locationCode": 1,
"yearMonth": "May/2021"
},
"hours": "10"
},
{
"ppmInfoId": {
"changeOrderId": 0,
"locationCode": 1,
"yearMonth": "June/2021"
},
"hours": "20"
}, {
"ppmInfoId": {
"changeOrderId": 0,
"locationCode": 2,
"yearMonth": "May/2021"
},
"hours": "10"
},
{
"ppmInfoId": {
"changeOrderId": 0,
"locationCode": 3,
"yearMonth": "May/2021"
},
"hours": "10"
}
]
输入数组 1:
this.responseValue = [
{
locationCode: '1',
locationType: 'Onsite',
ppmDetailsToList: [
{
hours: 0,
changeOrderId: null,
yearMonth: 'May/2021',
},
{
hours: 0,
changeOrderId: null,
yearMonth: 'June/2021',
},
]
},
{
locationCode: '2',
locationType: 'Offshore',
ppmDetailsToList: [
{
hours: 0,
changeOrderId: null,
yearMonth: 'May/2021',
},
]
},
{
locationCode: '3',
locationType: 'offsite',
ppmDetailsToList: [
{
hours:0,
changeOrderId: null,
yearMonth: 'May/2021',
locationCode: 0
},
]
}
];
输入数组 2:
[{ "Onsite": [ 10, 20 ], "Offshore": [ 10 ], "offsite": [ 10 ] }]
解决方案
const array1 = [{
locationCode: '1',
locationType: 'Onsite',
ppmDetailsToList: [{
hours: 0,
changeOrderId: null,
yearMonth: 'May/2021',
}, ]
},
{
locationCode: '2',
locationType: 'Offshore',
ppmDetailsToList: [{
hours: 0,
changeOrderId: null,
yearMonth: 'May/2021',
}, ]
},
{
locationCode: '3',
locationType: 'offsite',
ppmDetailsToList: [{
hours: 0,
changeOrderId: null,
yearMonth: 'May/2021',
locationCode: 0
}, ]
}
];
const array2 = [{
"Onsite": [10],
"Offshore": [10],
"offsite": [10]
}]
const result = {
ppmInfo: array1.map(({
locationCode,
locationType,
ppmDetailsToList: [{ hours, changeOrderId, yearMonth }]
}) =>({
hours: array2[0][locationType][0],
ppmInfoId: {
changeOrderId: changeOrderId || 0,
locationCode,
yearMonth
}
}))
}
console.log(result)
推荐阅读
- r - bookdown::publish_book - 在 Rstudio 中发布 Rmarkdown 时出错
- c - IPv4 总长度超过了特制数据包的数据包长度(64 字节)
- node.js - NodeJS 内存增长 - (系统)内存泄漏?
- c++ - 如何使用 QWebEngineView 忽略 SSL 证书错误
- php - sql 数据库中雄辩的 laravel 中文支持
- javascript - 在 DomParser 中使用 hasAttribute
- php - 使用 WebfactoryPolyglotBundle 会导致错误“在类 'AppBundle\Entity\Film' 上找不到字段 'id' 的映射。”
- c# - 如何将后端状态消息传达给前端?
- scala.js - binding.scala + scalatags 中的反应组件
- javascript - 如何通过组合字符和数字生成 UniqueID,并在 ECMAScript 中应用填充