简体   繁体   中英

Javascript Renaming object properties in Object.assign() function

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?

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
    }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM