我在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" }];

最佳答案

您的问题与React无关。但是无论如何,这里是这样:



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>

10-07 12:55
查看更多