1.在数组里面按顺序插入相对应的值,不满足补 0 ,【通常用于图表渲染 Y 轴】
// 先定义按顺序的横轴
var xArr=['01',"02","03","04","05","06"];
var obj=[
{
pkey:'01',
value:18
},
{
pkey:'03',
value:33
},
{
pkey:'06',
value:23
},
]
// 先处理数组
let temp={}
for(var key in obj){
temp[obj[key].pkey]=obj[key].value
}
//temp {01: 18, 03: 33, 06: 23}
let yArr=[]
for(var i=0;i<xArr.length;i++){
// 不满足补0
yArr.push(temp[xArr[i]]?temp[xArr[i]]:0)
}
// yArr[18, 0, 33, 0, 0, 23]
2.将数组转换成所需要的对象
var valList = [1,2,3,4,5].map(function(v){
return '"k":' + v;
})
var json = JSON.parse('[{' + valList.join('},{') + '}]');
console.log(json)
// (5) [{…}, {…}, {…}, {…}, {…}]
0: {k: 1}
1: {k: 2}
2: {k: 3}
3: {k: 4}
4: {k: 5}