1

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?

1 Answer 1

3

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
    }));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.