以下代码采用两个数组(fields
和photos
),获取其字段的名称和值,并将它们添加到新数组(panoramas
):
功能:
const panoramas = this.uploads.finished.map(photos => {
let panorama = {}
fields.forEach(field => { panorama[field.name] = field.value })
photos.forEach(photo => { panorama[photo.name] = photo.value })
return panorama
})
输入:
fields
:
[{
name: "name"
type: "hidden"
value: ""
}, {
name: "description"
type: "hidden"
value: ""
}, {
name: "photo"
type: "file"
value: ""
}, {
name: "photo2"
type: "file"
value: ""
}]
photos
:
[{
name: "photo"
value: "1.png"
}, {
name: "photo2"
value: "2.jpg"
}]
输出:
panoramas:
[{
name: "name"
type: "hidden"
value: ""
}, {
name: "description"
type: "hidden"
value: ""
}, {
name: "photo"
type: "file"
value: "1.png"
}, {
name: "photo2"
type: "file"
value: "2.png"
}]
正如您所看到的,我在forEach
内使用了两个map
循环。有没有办法只使用一个forEach
?
答案 0 :(得分:3)
fields.concat(photos).forEach(obj => { panorama[obj.name] = obj.value });