How to do it dynamically if we have more objects in input data?
I have dataset array with multiple objects inside it, and objects can be any number.
and I have to convert this data into newDataset object with dynamic array inside of it, this array of number dependence on dataset array's objects. I have done this if we have known number of dataset array's objects. for example: see below.
// Input data have dynamic more objects.
var dataset = [
{
date: "1 Jan 2020",
data1: 44,
data2: 40,
},
{
date: "2 Jan 2020",
data1: 37,
data2: 60,
},
{
date: "3 Jan 2020",
data1: 75,
data2: 90,
},
];
var newDataset = {};
// // Output data should be in this form.
// var newDataset = {
// date: ["1 Jan 2020", "2 Jan 2020", "3 Jan 2020"],
// data1: [44, 37, 75],
// data2: [40, 60, 90],
// };
// write your code below
var date = [];
var data1 = [];
var data2 = [];
for (var i = 0; i < dataset.length; i++) {
date.push(dataset[i].date);
data1.push(dataset[i].data1);
data2.push(dataset[i].data2);
}
newDataset.date = date;
newDataset.data1 = data1;
newDataset.data2 = data2;
console.log(newDataset);
//end of your code
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…