-1

My database gives me the following data:

var responses = [
          { comment: 'Yes', uid: '5hg' },
          { comment: 'Maybe', uid: 'f1' },
          { comment: 'No', uid: 'b1k2' },
          { comment: 'Yes', uid: '6t2' },
          { comment: 'Yes', uid: 'hd1' },
        ];

var users = [
          { name: 'Trevor Hansen', group: 'Group 1', uid: 'f1' },
          { name: 'Britta Holt', group: 'Group 2', uid: '5hg' },
          { name: 'Jane Smith ', group: 'Group 2', uid: '6t2' },
          { name: 'Sandra Adams', group: 'Group 1', uid: 'c92c' },
          { name: 'Ali Connors', group: 'Group 1', uid: 'b2' },
          { name: 'John Smith', group: 'Group 2', uid: '9l2' },
          { name: 'Sandra Williams', group: 'Group 2', uid: 'hd1' },
          { name: 'Tucker Smith', group: 'Group 1', uid: 'b1k2' },
        ];

Because I store all of my user data only in users[] for different purposes I need to add some information to responses[] about the user (like their name and group). The uid is unique and can be used to match the data to a user.

Obviously there are less responses than users in responses[]. This should not affect my function and is an expected behavior.

This is the desired output:

var output = [
          { comment: 'Yes', uid: '5hg', name: 'Britta Holt', group: 'Group 2' },
          { comment: 'Maybe', uid: 'f1', name: 'Trevor Hansen', group: 'Group 1' },
          { comment: 'No', uid: 'b1k2', name: 'Tucker Smith', group: 'Group 1' },
          { comment: 'Yes', uid: '6t2', name: 'Jane Smith ', group: 'Group 2' },
          { comment: 'Yes', uid: 'hd1', name: 'Sandra Williams', group: 'Group 2' },
        ];

How can this be done? Any help is appreciated!

mcd
  • 706
  • 4
  • 25

1 Answers1

1

you can try for example:

const output = responses.map(response => {
  const user = users.find(u => u.uid === response.uid);
  return {...response, ...user}
})

or single liner:

const output = responses.map(response => ({...response, ...users.find(u => u.uid === response.uid)}));
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
eamanola
  • 364
  • 1
  • 10
  • 1
    or single liner: var output = responses.map(response => ({...response, ...users.find(u => u.uid === response.uid)})) – eamanola Mar 12 '21 at 11:36