我有以下数据作为json:
"Table":[
{
"AF":2000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":100.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":15000.00
"RegionNumber":2
"RegionName":"Istanbul"
},
{
"AF":31000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":11000.00
"RegionNumber":2
"RegionName":"Istanbul"
}
]
我想在Javascript中按以下格式排列数据。
series: [{
name: 'Black Sea',
data: [2000, 100, 31000],
stack: 'Bookings'
}, {
name: 'Istanbul',
data: [15000,11000,0],
stack: 'Bookings'
}]
我如何完成这种转变?
答案 0 :(得分:1)
这几乎可以满足您的要求,也可以使用Ramda.js
const data = {
Table: [
{
AF: 2000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 100,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 15000,
RegionName: "Istanbul",
RegionNumber: 2
},
{
AF: 31000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 11000,
RegionName: "Istanbul",
RegionNumber: 2
}
]
}
const transfromTableData =
R.pipe(
R.groupBy(R.prop("RegionName")),
R.map(R.pluck("AF")),
R.toPairs,
R.map(R.zipObj(["name", "data"]))
)
const transfromData = (data) => ({
series: transfromTableData(data.Table)
})
console.log(transfromData(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
答案 1 :(得分:0)
纯JavaScript:
var memo = {}
for (var i in table) {
var item = table[i];
if (memo[item.RegionName] !== undefined) memo[item.RegionName].data.push(item.AF);
else memo[item.RegionName] = {
name: item.RegionName,
data: [item.AF],
stack: 'Bookings'
}
}
var result = {
series: []
};
for (var i in memo) {
result.series.push(memo[i]);
}
console.log(result);
答案 2 :(得分:0)
我在Web方法中将自定义对象的数组传递给List,它运行得很好。
我猜,由于属性名称周围的引号,你有一个小的JSON格式问题。尝试将您的对象更改为:
var scoresList = [{TraitID:1, TraitScore:2}, {TraitID:2, TraitScore:5}];
并将您的数据行更改为:
data: JSON.stringify({ scores : scoresList }),
希望有帮助...
更新:工作示例......
<script type="text/javascript">
$(function () {
var scoresList = [{ TraitID: 1, TraitScore: 2 }, { TraitID: 2, TraitScore: 5}];
$.ajax({ type: "POST",
url: "Tryouts.aspx/Test",
data: JSON.stringify({ scores: scoresList }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d == true) {
alert("success!!!!!");
} else {
alert("problem!!!!!!!!!");
}
},
error: function (xhr) {
alert("ERROR");
}
});
});
</script>
这是代码隐藏:
public class Score
{ // default constructor
public Score() { }
public int TraitID { get; set; }
public double TraitScore { get; set; }
}
[WebMethod]
public static bool Test( List<Score> scores )
{
return true;
}