问题描述
我下面有一个这样的数组
[
{
"Date": "2020-07","data": [
{
"id": "35ebd073-600c-4be4-a750-41c4be5ed24a","Date": "2020-07-03T00:00:00.000Z","transactionId": "13","transactionType": "Payment","amount": 1500
}
]
},{
"Date": "2020-07","data": [
{
"id": "4e126519-e27b-4e82-bb81-689c7dc63c9b","Date": "2020-07-02T00:00:00.000Z","transactionId": "4","amount": 1000
}
]
},{
"Date": "2020-06","data": [
{
"id": "646d6497-9dea-4f27-896e-a45d97a252ea","Date": "2020-06-04T00:00:00.000Z","transactionId": "14","data": [
{
"id": "cf44e27f-2111-462d-b3bd-420a193745b8","Date": "2020-06-02T00:00:00.000Z","transactionId": "5","amount": 1000
}
]
}
]
这里有键Date
,并且同一日期键有两个值。现在我想如果Date是相同的,那么数据数组记录应该合并。
所以我希望输出为
[
{
"Date": "2020-07","amount": 1500
},{
"id": "4e126519-e27b-4e82-bb81-689c7dc63c9b",{
"id": "cf44e27f-2111-462d-b3bd-420a193745b8","amount": 1000
}
]
}
]
请告诉我最佳的实现方式吗?
解决方法
您可以使用dictionary
并轻松检查密钥是否已存在,然后追加新数据,否则您将日期添加为新密钥。
var dict = {};
if (!("xxxx-xx" in dict)){ //if the key is not the dict
dict["xxxx-xx"] = [{ //we are storing an array because we want to add other later
id: "....",transactionId: "..."
//etc...
}]
}
else { //if the key already exists,we push new data to the array
dict["xxxx-xx"].push({ //you can use push because is an array of objects
id: "....",transactionId: "..."
//etc...
})
}
我希望它会有所帮助。 array
不太方便检查键是否已存在和避免重复(默认情况下为dict / object)。
arr =您的数据集
obj =这将是您的输出
arr.forEach((elem) => {
if(obj[elem.Date]) {
obj[elem.Date].data.push(elem.data);
} else {
obj[elem.Date] = {
data: [elem.data]
}
}
});
,
首先,您必须按属性Date
对对象数组进行分组。然后按[Date,groupsByDate]
的键值对分组,然后从每个组中获取数据
const res = _.chain(data)
.groupBy("Date")
.toPairs()
.map(([key,value]) => ({
Date: key,data: _.flatMap(value,"data"),}))
.value()
完整代码
const data = [
{
Date: "2020-07",data: [
{
id: "35ebd073-600c-4be4-a750-41c4be5ed24a",Date: "2020-07-03T00:00:00.000Z",transactionId: "13",transactionType: "Payment",amount: 1500,},],{
Date: "2020-07",data: [
{
id: "4e126519-e27b-4e82-bb81-689c7dc63c9b",Date: "2020-07-02T00:00:00.000Z",transactionId: "4",amount: 1000,{
Date: "2020-06",data: [
{
id: "646d6497-9dea-4f27-896e-a45d97a252ea",Date: "2020-06-04T00:00:00.000Z",transactionId: "14",data: [
{
id: "cf44e27f-2111-462d-b3bd-420a193745b8",Date: "2020-06-02T00:00:00.000Z",transactionId: "5",]
const res = _.chain(data)
.groupBy("Date")
.toPairs()
.map(([key,}))
.value()
console.log(JSON.stringify(res,null,2))
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>