gpt4 book ai didi

javascript - Jquery - 数据从垂直格式到水平格式

转载 作者:行者123 更新时间:2023-12-03 11:18:36 26 4
gpt4 key购买 nike

Fiddle

sql中的数据是以垂直格式存储的,我想以水平格式显示它。

这就是数据在 SQL Server 中的存储方式:- enter image description here

我正在使用 angularjs ui-grid 来显示数据 http://ui-grid.info/docs/#/tutorial/101_intro 。我使用 ajax 从 sql 中获取这些数据,因此将其转换为 JSON 格式。

var jqxhr = jq.ajax({
type: "POST",
url: "/Main/getData",
data: { catId: catId },
success: function (data) {
var dataObj = jQuery.parseJSON(data);
....
});

这就是我需要最终数据格式的方式。

 $scope.myData = [
{
"EmployeeId": "1",
"OTHINC1": "200",
"OTHINC2": "100"
},
{
"EmployeeId": "2",
"OTHINC1": "300",
"OTHINC2": "100"
}
];

最佳答案

以下是您如何实现 - fiddle link (参见console.log)

var formattedData = [];
for(var i = 0; i < data.length; i++) {
var obj;
var matchedIndex = indexOfByProp(formattedData, data[i].EmployeeId, 'EmployeeId');
if(matchedIndex === -1) { //new employee
obj = {
"EmployeeId" : data[i].EmployeeId
};
obj[data[i].FieldName] = data[i].Value;//adding value as a property
formattedData.push(obj);

} else { //add the new property to obj
obj = formattedData[matchedIndex];
obj[data[i].FieldName] = data[i].Value;
}
}
console.log(formattedData);
function indexOfByProp(arr, val, prop) {
for(var i = 0; i < arr.length; i++) {
if(arr[i][prop] === val) {
return i;
}
}
return - 1;
}

关于javascript - Jquery - 数据从垂直格式到水平格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27222172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com