简体   繁体   English

如何将一组对象组合到另一个对象数组中,同时还组合了公共键

[英]How can i combine an array of objects into another array of objects while also combining the common keys

I'm trying sort an array of objects into another array of objects but also combining the common keys (in this case the key updatedAt) 我正在尝试将对象数组排序到另一个对象数组中,但也要将公共键组合在一起(在本例中为key更新的密钥)

Example: 例:

const arr = [
     { id: '5c65ded933767500010c22a6',
       createdAt: '2019-02-14T21:34:17.181Z',
       updatedAt: '2019-02-14T21:38:01.251Z',
       userId: '5b213937cdcd57002d128aa5',
       phoneNumber: '(514) 578-9586',
       orderId: '5c65ded346e0fb000698f102',
       paymentMethods: [],
       shopName: 'test1',
       amount: 3.47,
       type: 'CASHBACK',
       status: 'COMPLETED',
       currency: 'CAD' },
     { id: '5c5226777de2c4000139de58',
       createdAt: '2019-01-30T22:34:31.648Z',
       updatedAt: '2019-01-30T22:37:01.246Z',
       userId: '5b213937cdcd57002d128aa5',
       phoneNumber: '(514) 578-9586',
       orderId: '5c52267146e0fb0006dc852a',
       paymentMethods: [],
       shopName: 'test2',
       amount: 0.24,
       type: 'CASHBACK',
       status: 'COMPLETED',
       currency: 'CAD' },
     { id: '5c019c07c9e77c0001c5ceb8',
       createdAt: '2018-11-30T20:22:31.392Z',
       updatedAt: '2019-01-17T15:53:24.410Z',
       userId: '5b213937cdcd57002d128aa5',
       phoneNumber: null,
       orderId: '5c019bfcc9e77c0006ba4f77',
       paymentMethods: [],
       shopName: 'test3',
       amount: 1.12,
       type: 'CASHBACK',
       status: 'COMPLETED',
       currency: 'CAD' },
     { id: '5c0195cac9e77c0001c5ceb5',
       createdAt: '2018-11-30T19:55:54.646Z',
       updatedAt: '2019-01-17T15:53:12.624Z',
       userId: '5b213937cdcd57002d128aa5',
       phoneNumber: null,
       orderId: '5c0195bfc9e77c0006b3873f',
       paymentMethods: [],
       shopName: 'test4',
       amount: 1.15,
       type: 'CASHBACK',
       status: 'COMPLETED',
       currency: 'CAD' } ]

into: 成:

[
  {
    date: '2019-01-30T22:37:01.246Z',
    transactions: [
     {'...THE TRANSACTIONS THAT OCURED ON THE SAME DATE...'},
     {'...THE TRANSACTIONS THAT OCURED ON THE SAME DATE...'},
     {'...THE TRANSACTIONS THAT OCURED ON THE SAME DATE...'},
    ]
  },
  {
    date: '2019-01-14T22:37:01.246Z',
    transactions: [
     {'...THE TRANSACTIONS THAT OCURED ON THE SAME DATE...'},
     {'...THE TRANSACTIONS THAT OCURED ON THE SAME DATE...'},
     {'...THE TRANSACTIONS THAT OCURED ON THE SAME DATE...'},
    ]
  }
]

I've tried using multiple loops but it just seems inefficient so i later tried using lodash and that also seems ineficient 我已经尝试过使用多个循环,但它似乎效率低下,所以我后来尝试使用lodash,这似乎也是无效的

here is my attempt using lodash 这是我尝试使用lodash

const mapDaysToTransactions = (transactions) => {
  const mappedTransactions = transactions.reduce((acc, next) => {
  return acc.concat({
    day: next.updatedAt,
    transactions: next
  })
}, [])
const groupedBydays = _.groupBy(mappedTransactions, el => moment(el.day).format('MMMM, d'))
  return Object.keys(groupedBydays).map(d => {
    return {
      date: groupedBydays[d][0].day,
      transactions: _.flattenDeep(groupedBydays[d])
    }
  })
}

I get the expected result with the function above but i want to know if there is a 'better' more optimal way to go about a situation like this. 我用上面的函数得到了预期的结果,但我想知道是否有更好的“更好”的方法来解决这种情况。

UPDATE: Another solution using a single reduce 更新:使用单个reduce的另一个解决方案

const mapDaysToTransactions = (transactions) => {

  const mapped = transactions.reduce((acc, next) => {
  return acc.concat({
    day: next.updatedAt,
    transactions: next
  })
  }, [])

  return mapped.reduce((acc, transaction) => {
    const date = moment(transaction.day).format('MMMM, d');
    const iso = transaction.day
    const index = acc.findIndex(t => t.date === date);
    const idx = acc.indexOf(date)
  if (idx !== -1) {
    const transactionsByDate = acc[idx];
    const newAcc = [
      ...acc.slice(0, idx),
      ...acc.slice(idx + 1, acc.length),
    ]
    return newAcc.concat({
      date,
      day: iso,
      transactions: transactionsByDate.transactions.concat(transaction),
    });
  }

  return acc.concat({
    date,
    day: iso,
    transactions: [transaction],
  });
 }, []);
}


In reduce you're creating a new array first instead you can use object and group values based on date and than create an array reduce您首先要创建一个新数组,而不是基于date使用object和组值,而是创建一个数组

 const arr = [{ id: '5c65ded933767500010c22a6',createdAt: '2019-02-14T21:34:17.181Z',updatedAt: '2019-02-14T21:38:01.251Z',userId: '5b213937cdcd57002d128aa5',phoneNumber: '(514) 578-9586',orderId: '5c65ded346e0fb000698f102',paymentMethods: [],shopName: 'test1',amount: 3.47,type: 'CASHBACK',status: 'COMPLETED',currency: 'CAD' },{ id: '5c5226777de2c4000139de58',createdAt: '2019-01-30T22:34:31.648Z',updatedAt: '2019-01-30T22:37:01.246Z',userId: '5b213937cdcd57002d128aa5',phoneNumber: '(514) 578-9586',orderId: '5c52267146e0fb0006dc852a',paymentMethods: [],shopName: 'test2',amount: 0.24,type: 'CASHBACK',status: 'COMPLETED',currency: 'CAD' },{ id: '5c019c07c9e77c0001c5ceb8',createdAt: '2018-11-30T20:22:31.392Z',updatedAt: '2019-01-17T15:53:24.410Z',userId: '5b213937cdcd57002d128aa5',phoneNumber: null,orderId: '5c019bfcc9e77c0006ba4f77',paymentMethods: [],shopName: 'test3',amount: 1.12,type: 'CASHBACK',status: 'COMPLETED',currency: 'CAD' },{ id: '5c0195cac9e77c0001c5ceb5',createdAt: '2018-11-30T19:55:54.646Z',updatedAt: '2019-01-17T15:53:12.624Z',userId: '5b213937cdcd57002d128aa5',phoneNumber: null,orderId: '5c0195bfc9e77c0006b3873f',paymentMethods: [],shopName: 'test4',amount: 1.15,type: 'CASHBACK',status: 'COMPLETED',currency: 'CAD' } ] let final = arr.reduce((op,inp) => { let date = inp.updatedAt.substr(0,10) op[date] = op[date] || {date, transaction:[]} op[date].transaction.push(inp) return op },{}) console.log(Object.values(final)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何汇总对象数组中的公用键? - How can I sum common keys in an array of objects? 如何将具有相同键的对象数组合到一个对象中? - How can I combine an array of objects with the same keys into one object? 如何在比较另一个对象的同时过滤对象数组? - How can I filter through an array of objects while also comparing another object? 如何在所有对象的键相同且值可能不同的情况下将对象数组转换为单个 object - How can I convert an array of objects into single object while keys of all the objects are same and value may differ 如何组合对象数组中的每个值? - How can I combine each value from an array of objects? 如何通过键“多重排序”Javascript中的对象数组 - How can I "multi sort" an array of objects in Javascript by keys 如何在对象数组中获取具有唯一值的键? (JavaScript) - How can I get keys with unique values in an array of objects? (JavaScript) 如何在数组中找到具有相同键值的对象? - How can I find objects with same keys values in array? 给定对象数组,如何根据键在数组内合并对象? - Given an array of objects how can I merge Objects within the array based of the keys? 如何将对象数组转换为具有相同值但具有修改键的对象数组? - How can I convert an array of objects into an array of objects with the same values but with modified keys?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM