JavaScript merging objects by id

前端 未结 16 2005
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 10:26

    Already there are many great answers, I'll just add another one which is from a real problem I needed to solve yesterday.

    I had an array of messages with user ids, and one array of users containing users' names and other details. This is how I managed to add user details to the messages.

    var messages = [{userId: 2, content: "Salam"}, {userId: 5, content: "Hello"},{userId: 4, content: "Moi"}];
    var users = [{id: 2, name: "Grace"}, {id: 4, name: "Janetta"},{id: 5, name: "Sara"}];
    
    var messagesWithUserNames = messages.map((msg)=> {
      var haveEqualId = (user) => user.id === msg.userId
      var userWithEqualId= users.find(haveEqualId)
      return Object.assign({}, msg, userWithEqualId)
    })
    console.log(messagesWithUserNames)
    

提交回复
热议问题