首页 > 解决方案 > 将多个数组 .map 合并为一个

问题描述

我有一组 javascript 对象

var arr =  [ 
        { 
          query_result_id: 25,
          author_email: 'john@example.com'
        },
       { 
          query_result_id: 28,
          author_email: 'eric@example.com'
        },
  ]

.map用来在每个 javascript 对象上输入新值

arr
        .map( s => s["status"] = "dev")
        .map( s => s["customer_id"] = customerId)
        .map( s => s["email_nb"] = emailId)
        //and so on for about 10 new key/values

输出是:

 var arr =  [ 
            { 
              query_result_id: 25,
              author_email: 'john@example.com',
              status: dev,
              customer_id: 45,
              email_nb: 45
            },
           { 
              query_result_id: 28,
              author_email: 'eric@example.com',
              status: dev,
              customer_id: 78,
              email_nb: 56
            },
      ]

在 javascript 中是否可以不链接 10.map而是一个单一的操作以使其更清洁,甚至可能更高性能/更快?

标签: javascript

解决方案


当您打算在数组中保留相同的值时,您不应该使用 map。

map旨在重新创建一个新数组,其值取决于源数组。你想要做的是对每个元素应用一个forEach函数

这是使用 foreach 的方法:

let customerId = "customerId"
let emailId = "emailId"

var arr =  [{query_result_id: 25,author_email: 'john@example.com'},
            {query_result_id: 28,author_email: 'eric@example.com'}]

arr.forEach( s => {
  s["status"] = "dev"
  s["customer_id"] = customerId
  s["email_nb"] = emailId
})
        
console.log(arr)


推荐阅读