简体   繁体   中英

Consolidate two state arrays in React

I have two arrays in state , I would look like the final result as follows

this.state = {
    one: [{ "month": "January", "reportCode": "XYZ", "fld1": "17", "fld2": "24" },
          { "month": "February", "reportCode": "XYZ", "fld1": "18", "fld2": "15" }],
    two: [{ "reportCode": "XYZ", "fld": "fld1", "val": "Profit" },
          { "reportCode": "XYZ", "fld": "fld2", "val": "Loss" },
          { "reportCode": "XYZ", "fld": "fld3", "val": "Total" }]
};
//code here
const result = [{ "month": "January", "Profit": "17", "Loss": "24" },
                { "month": "February", "Profit": "18", "Loss": "15" }];

Your question has barely anything to do with React . But anyway, here goes:

 this.state = { one: [{ "month": "January", "reportCode": "XYZ", "fld1": "17", "fld2": "24" }, { "month": "February", "reportCode": "XYZ", "fld1": "18", "fld2": "15" }], two: [{ "reportCode": "XYZ", "fld": "fld1", "val": "Profit" }, { "reportCode": "XYZ", "fld": "fld2", "val": "Loss" }, { "reportCode": "XYZ", "fld": "fld3", "val": "Total" }] }; const targetResult = [{ "month": "January", "Profit": "17", "Loss": "24" }, { "month": "February", "Profit": "18", "Loss": "15" }]; const result = this.state.one.map( ({ month, reportCode, fld1, fld2 }) => { const key1 = this.state.two.find(({ fld }) => fld === 'fld1').val; const key2 = this.state.two.find(({ fld }) => fld === 'fld2').val; return { month, [key1]: fld1, [key2]: fld2, }; }, ); console.log('result: ', result); console.log('is-correct: ', _.isEqual(result, targetResult)); 
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script> 

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