0

Im trying to build this array:


[{
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"}
]
}];

I have this json data


labels = ["Workorder 1", ... , "Workorder 10"]
start = ["2019-01-01", ... ,"2019-01-25" ]
end= ["2019-01-10", ... ,"2019-01-25"]

this is how far I got:


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);

which has this as output:


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"}
]

Thank you for any help

7
  • Your question is very unclear. Please state your problem clearly. Commented Dec 2, 2019 at 10:10
  • Hi @User9023 check if this helps. Commented Dec 2, 2019 at 10:10
  • what value does labels contain, question detail is missing, please provide full detail Commented Dec 2, 2019 at 10:16
  • then name key is not there in your expected output but you trying to add it in your code Commented Dec 2, 2019 at 10:37
  • @NarendraChouhan added to my question Commented Dec 2, 2019 at 10:39

2 Answers 2

0

This will Work For you, Try this

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)

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

You can check it in browser or in REPL mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.