如何合并这两个forEach循环(只使用一个)?

时间:2016-12-06 01:53:43

标签: javascript loops

以下代码采用两个数组(fieldsphotos),获取其字段的名称和值,并将它们添加到新数组(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

1 个答案:

答案 0 :(得分:3)

fields.concat(photos).forEach(obj => { panorama[obj.name] = obj.value });