gpt4 book ai didi

javascript - 复杂的java脚本操作,新对象的数组对象排序

转载 作者:行者123 更新时间:2023-12-03 09:29:25 24 4
gpt4 key购买 nike

我有一组对象,需要为另一项工作 reshape 它们。需要一些操作来通过一个函数进行转换。我创建了 plunker https://jsbin.com/himawakaju/edit?html,js,console,output

主要因素是月份、国家/地区及其“AC”值。

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},

{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},

{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];

var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];

最佳答案

var actual = [{
"country": "UK",
"month": "JAN",
"SR": "John P",
"AC": "24",
"PR": "2",
"TR": 1240
}, {
"country": "AUSTRIA",
"month": "JAN",
"SR": "Brad P",
"AC": "64",
"PR": "12",
"TR": 1700
}, {
"country": "ITALY",
"month": "JAN",
"SR": "Gim P",
"AC": "21",
"PR": "5",
"TR": 900
},

{
"country": "UK",
"month": "FEB",
"SR": "John P",
"AC": "14",
"PR": "4",
"TR": 540
}, {
"country": "AUSTRIA",
"month": "FEB",
"SR": "Brad P",
"AC": "24",
"PR": "12",
"TR": 1700
}, {
"country": "ITALY",
"month": "FEB",
"SR": "Gim P",
"AC": "22",
"PR": "3",
"TR": 600
},

{
"country": "UK",
"month": "MAR",
"SR": "John P",
"AC": "56",
"PR": "2",
"TR": 1440
}, {
"country": "AUSTRIA",
"month": "MAR",
"SR": "Brad P",
"AC": "24",
"PR": "12",
"TR": 700
}, {
"country": "ITALY",
"month": "MAR",
"SR": "Gim P",
"AC": "51",
"PR": "5",
"TR": 200
}];
var monthsArray = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];

function converter(actual) {
var desiredArr = [];
for (var i = 0; i < monthsArray.length; ++i) {
debugger
var obj = {};
var innerObj = {};
var month = '';
for (var j = 0; j < actual.length; ++j) {
if (monthsArray[i] == actual[j].month.toLowerCase()) {
month = actual[j].month;
innerObj[actual[j].country] = actual[j].AC;

}
}
if (month.length > 0) {
obj.month = month;
obj.val = innerObj;
desiredArr.push(obj);
}
}
return desiredArr;
}
alert(JSON.stringify(converter(actual)));

关于javascript - 复杂的java脚本操作,新对象的数组对象排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31563983/

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