Reputation: 819
I have a list called 'series' which has all the data inside it. I am parsing in 'periodList' another string list and looping through this periodList list and using .filter to filter the main dataset (series). This is returning correctly. I am now trying to add items to the object myArray using .map but its not giving me my expected outcome.
I have attempted the below:
function chartBuilder(series, periodList) {
var myArray = {}; //creates **a new empty object**
for (var i in periodList) {
var seriessplit = series.filter(function (type) {
return type.pc === periodList[i];
});
myArray = seriessplit.map(elem => (
{
name: elem.pc,
type: chartType,
data: [elem.mid]
}
));
console.log(myArray);
}
}
This currently gives me an output :
Array(7)
0: {name: "Oct 20", type: "Line", data: Array(1)}
1: {name: "Oct 20", type: "Line", data: Array(1)}
2: {name: "Oct 20", type: "Line", data: Array(1)}
3: {name: "Oct 20", type: "Line", data: Array(1)}
4: {name: "Oct 20", type: "Line", data: Array(1)}
5: {name: "Oct 20", type: "Line", data: Array(1)}
6: {name: "Oct 20", type: "Line", data: Array(1)}
But what I was expecting is for the data to be combined to look like the below:
{
name: "Oct 20",
type: "Line",
data: [45,45,24,25,64,65,87]
}
Where am I going wrong? Seems to be creating a new item in the object for each new data value
Upvotes: 0
Views: 46
Reputation: 16447
You want to map only data
not the whole array/object:
const series = [
{pc: "Oct 20", mid: 45},
{pc: "Oct 20", mid: 45},
{pc: "Oct 20", mid: 24},
{pc: "Oct 20", mid: 25},
{pc: "Oct 21", mid: 145},
{pc: "Oct 21", mid: 145},
{pc: "Oct 21", mid: 124},
{pc: "Oct 21", mid: 125}
];
const chartType = "Line";
function chartBuilder(series, periodList) {
for (let i in periodList) {
const seriessplit = series.filter(({pc}) => pc === periodList[i]);
const myArray = {
name: periodList[i],
type: chartType,
data: seriessplit.map(({mid}) => mid)
};
console.log(myArray);
}
}
chartBuilder(series, ["Oct 20", "Oct 21"]);
If you need an array of this you can map twice:
const series = [
{pc: "Oct 20", mid: 45},
{pc: "Oct 20", mid: 45},
{pc: "Oct 20", mid: 24},
{pc: "Oct 20", mid: 25},
{pc: "Oct 21", mid: 145},
{pc: "Oct 21", mid: 145},
{pc: "Oct 21", mid: 124},
{pc: "Oct 21", mid: 125}
];
const chartType = "Line";
function chartBuilder(series, periodList) {
return periodList.map(period => {
const seriessplit = series.filter(({pc}) => pc === period);
const myArray = {
name: period,
type: chartType,
data: seriessplit.map(({mid}) => mid)
};
console.log(myArray);
return myArray;
});
}
console.log(chartBuilder(series, ["Oct 20", "Oct 21"]));
Upvotes: 1