Reputation: 13
I'm trying to combine two arrays in a specific format, but I cant imagine what I'm doing wrong.
This is the output result that I would like to have:
[ data: [
{value: 100, name: 'January'},
{value: 30, name: 'February'},
{value: 150, name: 'March'},
{value: 85, name: 'April'},
{value: 60, name: 'May'},
{value: 20, name: 'June'}
],
radius: '50%' ]
This is my code:
var sales = ["100", "30", "150", "85", "60", "20"];
var months = ["January", "February", "March", "April", "May", "June"];
var rad = "50%";
var combined = sales.map(function combine(dataItem, index) {
return {
data: [{"value":dataItem, "name":months[index]}],
radius: rad
};
}).filter(function removeEmpty(item) {
return item.data.length;
});
console.log(combined);
Upvotes: 1
Views: 55
Reputation: 315
So, in your expected output, you are treating an array like an object. Try this for your expected result:
{data: [
{value: 100, name: 'January'},
{value: 30, name: 'February'},
{value: 150, name: 'March'},
{value: 85, name: 'April'},
{value: 60, name: 'May'},
{value: 20, name: 'June'}
],
radius: '50%'}
As to how to achieve the result, try this:
const sales = ["100", "30", "150", "85", "60", "20"],
months = ["January", "February", "March", "April", "May", "June"];
const combine = (s, m) => {
const arr = [];
for (let i = 0; i < Math.min(s.length, m.length); i++)
arr.push({ value: s[i], name: m[i] });
return arr;
};
const dataObj = {
data: combine(sales, months),
radius: "50%",
};
console.log(dataObj);
Upvotes: 0
Reputation: 25406
Just map
over it and add the value
and name
in the object.
var sales = ["100", "30", "150", "85", "60", "20"];
var months = ["January", "February", "March", "April", "May", "June"];
const data = sales.map((sale, i) => ({
value: parseInt(sale),
name: months[i],
}));
const result = {
data,
radius: "50%",
};
console.log(result);
Upvotes: 3