按以下格式排序我的json:
[{"x":"Jan-2017","y":41},{"x":"Feb-2017","y":20},{"x":"Mar-2017","y":45},{"x":"Apr-2017","y":29},{"x":"May-2017","y":59},{"x":"Jun-2017","y":378},{"x":"Jul-2017","y":354},{"x":"Aug-2017","y":398},{"x":"Sep-2017","y":390},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]
例如:
如果我的json如下:
[{"x":"Aug-2017","y":398},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]
结果应为:
[{"x":"Jan-2017","y":0},{"x":"Feb-2017","y":0},{"x":"Mar-2017","y":0},{"x":"Apr-2017","y":0},{"x":"May-2017","y":0},{"x":"Jun-2017","y":0},{"x":"Jul-2017","y":0},{"x":"Aug-2017","y":398},{"x":"Sep-2017","y":0},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]
任何帮助或暗示请一定会帮助我。
答案 0 :(得分:0)
您可以使用一个月的数组,按年和月对给定的数据进行排序,并使用该索引的数据数组来映射一整年,直到映射所有年份为止。
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
data = [{ x: "Aug-2017", y: 398 }, { x: "Oct-2017", y: 579 }, { x: "Nov-2017", y: 651 }, { x: "Dec-2017", y: 832 }]
.sort(({ x: a }, { x: b }) => {
var aa = a.split('-'),
bb = b.split('-');
return aa[1] - bb[1] || months.indexOf(aa[0]) - months.indexOf(bb[0]);
}),
index = 0,
year = data[0].x.slice(-4),
result = [];
do {
result.push(...months.map(month =>
data[index] && data[index].x.slice(0, 3) === month
? data[index++]
: { x: [month, year].join('-'), y: 0 }
));
} while (year++ < data[data.length - 1].x.slice(-4))
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
function sortElements(arr){
arr.sort((a, b) =>
new Date(a.x).getTime() - new Date(b.x).getTime()
);
}
答案 2 :(得分:0)
您可以利用moment.js来获取所有月份,然后遍历它并从中创建输出数组。
var input = [{"x":"Aug-2017","y":398},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]
var allmonths = moment.monthsShort();
var year = 2017;
var output = allmonths.map((el,i) => {
let temp;
return input.some((a) => a.x == el+"-"+year ? temp = a:false) ? temp:{x:el+"-"+year,y:0};
});
console.log(output);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>