[英]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 ? 这个结果是否可能在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. 您可以使用
array#reduce
ticketId
在新的对象累加器中基于ticketId
对数组对象进行分组,然后使用Object.values()
提取每个键的所有值。
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. 通过使用JavaScript编写和使用通用
Lookup
的实现,可以简化Array#reduce()
方法中的逻辑,然后将查找的键/值对映射到每组电子邮件中。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.