JavaScript之数据改造、后端只返回有数据的时段,没数据的时段需要前端自己补全、isArray、throw、forEach、hasOwnProperty、call、for in、push

function handleApacheECharts(existenceData) {
    
    
	if (!Array.isArray(existenceData)) throw new Error('not an array.');
	if (!existenceData[0].time) throw new Error('data error.');
	
	let obj = {
    
    
		1: {
    
     time: "08:00-09:00", value: 0, },
		2: {
    
     time: "09:00-10:00", value: 0, },
		3: {
    
     time: "10:00-11:00", value: 0, },
		4: {
    
     time: "11:00-12:00", value: 0, },
		5: {
    
     time: "12:00-13:00", value: 0, },
		6: {
    
     time: "13:00-14:00", value: 0, },
		7: {
    
     time: "14:00-15:00", value: 0, },
		8: {
    
     time: "15:00-16:00", value: 0, },
		9: {
    
     time: "16:00-17:00", value: 0, },
	},
		arr = {
    
    
			time: [],
			value: []
		};
	
	existenceData.forEach(item => {
    
    
		for (const key in item) {
    
    
			if (Object.hasOwnProperty.call(item, key)) {
    
    
				if (key === 'time') obj[item[key] - 7].value = item.value;
			}
		}
	});
	
	for (const j in obj) {
    
    
		if (Object.hasOwnProperty.call(obj, j)) {
    
    
			let item = obj[j];
			for (const key in item) {
    
    
				if (Object.hasOwnProperty.call(item, key)) {
    
    
					if (key === "time") {
    
    
						arr.time.push(item[key]);
					} else if (key === "value") {
    
    
						arr.value.push(item[key]);
					}
				}
			}
		}
	}
	
	return arr;
}

console.log(handleApacheECharts([{
    
     time: '10', value: 30 }, {
    
     time: '16', value: 10 }, {
    
     time: '16', value: 70 }]));
console.log(handleApacheECharts());
console.log(handleApacheECharts(''));
console.log(handleApacheECharts(1));
console.log(handleApacheECharts({
    
    }));
console.log(handleApacheECharts([1, 2]));

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/125154360