简体   繁体   English

在React中整合两个状态数组

[英]Consolidate two state arrays in React

I have two arrays in state , I would look like the final result as follows 我有两个数组处于state ,最终result如下所示

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 . 您的问题与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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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