简体   繁体   中英

Add the array objects field data in to single object in javascript

I getting this data into my response

var data=[ { id: 9,
    ticketId: 9,
    member: { id: 3, email: 'ganeshpandi@gmail.com' } },
  { id: 10,
    ticketId: 9,
    member: { id: 4, email: 'braveganesh128@gmail.com' } } ];

I want to send all the mail to all member email,

my expected result is:

var data=[ {
    ticketId: 9,
    member: {  email: ['ganeshpandi@gmail.com','braveganesh128@gmail.com'] } },
   ];

Is this result possible or not in foreach ?

You can use array#reduce to group your array object based on the ticketId in a new object accumulator, then using Object.values() extract all the values for each key.

 var data = [{ id: 9, ticketId: 9, member: { id: 3, email: 'ganeshpandi@gmail.com' } }, { id: 10, ticketId: 9, member: { id: 4, email: 'braveganesh128@gmail.com'}}], result = Object.values(data.reduce((r, {ticketId, member: {email}}) => { r[ticketId] = r[ticketId] || {ticketId, member:{email: []}}; r[ticketId].member.email.push(email); return r; },{})); console.log(result); 

By writing and using an implementation of a generic Lookup in JavaScript, you can simplify the logic in the Array#reduce() method and then map the key/value pairs of the lookup into each group of emails.

 const data = [{ id: 9, ticketId: 9, member: { id: 3, email: 'ganeshpandi@gmail.com' } }, { id: 10, ticketId: 9, member: { id: 4, email: 'braveganesh128@gmail.com' } }] const lookup = data.reduce( (lookup, { ticketId, member: { email } }) => lookup.add(ticketId, email), new Lookup() ) const result = [...lookup].map( ([ticketId, emails]) => ({ ticketId, member: [...emails] }) ) console.log(result) 
 <script src="https://cdn.rawgit.com/patrickroberts/4e6344a710569e4b7d280edc5684188d/raw/2aee1a65bfdbd7873bfacfe7ea3b5ef9a7f355f2/lookup.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM