JavaScript merging objects by id

前端 未结 16 1890
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:43

What\'s the correct way to merge two arrays in Javascript?

I\'ve got two arrays (for example):

var a1 = [{ id : 1, name : \"test\"}, { id : 2, name :         


        
16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 10:24

    Vanilla JS solution

    const a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
    const a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]
    
    const merge = (arr1, arr2) => {
      const temp = []
    
      arr1.forEach(x => {
        arr2.forEach(y => {
          if (x.id === y.id) {
            temp.push({ ...x, ...y })
          }
        })
      })
    
      return temp
    }
    
    console.log(merge(a1, a2))
    

提交回复
热议问题