Reputation: 566
I am trying to create a function that merges two arrays of object.
const obj = {
sales: [
{date: '01 FEB 2020', value: 1200},
{date: '05 FEB 2020', value: 3000},
{date: '10 FEB 2020', value: 2000},
{date: '15 FEB 2020', value: 2780},
{date: '20 FEB 2020', value: 1890},
{date: '25 FEB 2020', value: 2390},
{date: '29 FEB 2020', value: 3490},
],
cost: [
{date: '01 FEB 2020', value: 2000},
{date: '05 FEB 2020', value: 1200},
{date: '10 FEB 2020', value: 2800},
{date: '15 FEB 2020', value: 2280},
{date: '20 FEB 2020', value: 2000},
{date: '25 FEB 2020', value: 3000},
{date: '29 FEB 2020', value: 2490},
]}
as the value properties are same i want to change it to the parent name like: sales, cost
etc
Below is the function i am trying
processDualChartsData( data1, data2, newProp1, newProp2, newProp3, limit ){
let chartData = data1.map( (item, i) => Object.assign( {}, {newProp1: item.date, newProp2: item.value}, {newProp3: data2[i].value} ) )
return chartData.slice(0, limit)
}
And using the function as
let barChartData = this.processDualChartsData( sales, cost, 'date', 'visitor', 'profit', 7 )
I expected the return from it like:
[{date: "01 Feb 2020", sales: 40, cost: 45}, .... ]
But i am getting
[{newProp1: "01 Feb 2020", newProp2: 40, newProp3: 45}, {.....}, .....]
Can i manage it anyhow?
Upvotes: 1
Views: 272
Reputation: 386680
You need computed property names.
You could omit Object.assign
and use the new object directly.
let chartData = data1.map((item, i) => ({
[newProp1]: item.date,
[newProp2]: item.value,
[newProp3]: data2[i].value
}));
Upvotes: 3