我正在尝试构建此数组:
[{
id: "1", name: labels,
periods: [
{id:"1_1", start: "2018-01-05", end: "2018-01-25"},
{id:"1_2", start: "2018-01-28", end: "2018-02-22"},
{id:"1_3", start: "2018-03-03", end: "2018-03-25"}
]
}];
我有这个json数据
labels = ["Workorder 1", ... , "Workorder 10"]
start = ["2019-01-01", ... ,"2019-01-25" ]
end= ["2019-01-10", ... ,"2019-01-25"]
这是我走了多远:
var arr=[];
for ( var i=0; i<labels.length; i++){
newlab = labels[i];
newid = "id" + [i];
newstart = start[i];
newstop = end[i];
arr.push({ id:newid, name:newlab, start:newstart, end:newstop })
};
var data = {data:arr};
console.log(data);
具有以下输出:
data = [
{id: "id0", name: "Workorder 1", start: "2019-01-01", end: "2019-01-10"},
....
{id: "id9", name: "Workorder 10", start: "2019-11-25", end: "2019-01-14"}
]
谢谢您的帮助
答案 0 :(得分:0)
let labels="test_string",start = [],end=[],arr=[];
var arr=[],periods =[];
for ( var i=0; i<labels.length; i++){
obj = {};
obj.id= "1", obj.name= "labels"
newlab = labels[i];
newid = [i] + "_" + [i];
newstart = start[i];
newstop = end[i];
periods.push({ id:newid, name:newlab, start:newstart, end:newstop })
obj.periods = periods;
arr.push(obj)
};
let data = {data:arr};
console.log(data);
答案 1 :(得分:0)
这将为您工作,请尝试
var labels = ["Workorder 1", "Workorder 10"]
var start = ["2019-01-01", "2019-01-25"]
var end = ["2019-01-10", "2019-01-25"]
var obj = {}
var finalArray = []
for (var i = 1; i <= start.length; i++) {
var first = { id: i, name: 'labels' }
obj = { ...obj, ...first }
var periods = { id: i + '_' + i, name: labels[i - 1], start: start[i - 1], end: end[i - 1] }
if (obj.periods) {
obj.periods.push(periods)
} else {
obj.periods = [periods]
}
finalArray.push(obj)
}
var data = { data: finalArray };
console.log("finalOutput.............",data)