我有以下格式的 JSON 字符串。
{
"dt_total_score": [
{
"score": 60.8332,
"gText": "Total"
},
{
"score": 66.6666,
"gText": "Call Center"
},
{
"score": 66.6666,
"gText": "Restaurant reservation"
},
{
"score": 50,
"gText": "Arriving (Trams) - Experience or Observation"
},
{
"score": 60,
"gText": "Arrival & Parking Experience"
}
],
"dt_trend": [
{
"score": 60,
"gText": "Q1,2018",
"seriesName": "Arrival & Parking Experience",
"ONUM": 1
},
{
"score": 50,
"gText": "Q1,2018",
"seriesName": "Arriving (Trams) - Experience or Observation",
"ONUM": 1
},
{
"score": 66.6666,
"gText": "Q1,2018",
"seriesName": "Call Center",
"ONUM": 1
},
{
"score": 66.6666,
"gText": "Q1,2018",
"seriesName": "Restaurant reservation",
"ONUM": 1
},
{
"score": 60.8333,
"gText": "Q1,2018",
"seriesName": "Total",
"ONUM": 2
},
{
"score": 60.8333,
"gText": "Q4,2017",
"seriesName": "Total",
"ONUM": 2
},
{
"score": 60.8333,
"gText": "Q3,2017",
"seriesName": "Total",
"ONUM": 2
}
]
,
"dt_compartive":[
{
"gText":"Total",
"percentDiff":6083.0000
}
]
}
在上面的JSON中:
我必须以下列方式将基于类别的上述数据解析并合并到Javascript对象列表中。 请注意,此数据仅用于说明我希望输出的方式与上述数据无关
var dt_score_n_trend = [
{
gText:"Call Center",
score: 60.2223,
trendName:[ "Q1,2018", "Q2,2018"],
trendValue:[ 60, 70],
PercentageDiff:70
},
{
gText:"Call Center",
score: 60.2223,
trendName: [ "Q1,2018", "Q2,2018"],
trendValue:[ 60, 70],
PercentageDiff:70
}
];
到目前为止,我已经无意中尝试将JSON解析为Javascript对象,然后尝试合并它们。
如何将它们合并为上述方式?
编辑:更新了问题并删除了格式错误
答案 0 :(得分:1)
您可以使用array#reduce
根据dt_trend
对seriesName
数组进行分组。创建一个累加器对象,并为每个新seriesName
添加一个新对象,对于旧对象,更新趋势值。然后提取出所有的值。
var data = { "dt_total_score": [ { "score": 60.8332, "gText": "Total" }, { "score": 66.6666, "gText": "Call Center" }, { "score": 66.6666, "gText": "Restaurant reservation" }, { "score": 50, "gText": "Arriving (Trams) - Experience or Observation" }, { "score": 60, "gText": "Arrival & Parking Experience" } ], "dt_trend": [ { "score": 60, "gText": "Q1,2018", "seriesName": "Arrival & Parking Experience", "ONUM": 1 }, { "score": 50, "gText": "Q1,2018", "seriesName": "Arriving (Trams) - Experience or Observation", "ONUM": 1 }, { "score": 66.6666, "gText": "Q1,2018", "seriesName": "Call Center", "ONUM": 1 }, { "score": 66.6666, "gText": "Q1,2018", "seriesName": "Restaurant reservation", "ONUM": 1 }, { "score": 60.8333, "gText": "Q1,2018", "seriesName": "Total", "ONUM": 2 }, { "score": 60.8333, "gText": "Q4,2017", "seriesName": "Total", "ONUM": 2 }, { "score": 60.8333, "gText": "Q3,2017", "seriesName": "Total", "ONUM": 2 } ], "dt_compartive":[{"gText":"Total","percentDiff":6083.0000}]},
result = data.dt_trend.reduce((r,o) => {
r[o.seriesName] = r[o.seriesName] || {gText: o.seriesName, score: o.score, trendName: [], trendValue: []};
r[o.seriesName].trendName.push(o.gText);
r[o.seriesName].trendValue.push(o.score);
return r;
},{});
data.dt_compartive.forEach(o => {
result[o.gText].PercentageDiff = o.percentDiff;
});
var output = Object.values(result);
console.log(output);