javascript 无法获得在React js中合并对象数组内部的数组的预期结果

lrl1mhuk  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(92)

我有一个由2个对象组成的数组,每个对象又由一个对象数组组成。我需要在对象数组中合并它们。请在下面找到代码。

import React from 'react';
import './style.css';

export const data = [
  {
    accountNo: '1xxx',
    consolidateddata: [
      { name: 'Paypal', expiry: '05/13/2023' },
      { name: 'phonepay', expiry: '05/19/2023' },
    ],
  },
  {
    accountNo: '2xxx',
    consolidateddata: [{ name: 'Paytm', expiry: '05/25/2023' }],
  },
];
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      DataRows: [],
    };
    this.ProfileDetails = this.ProfileDetails.bind(this);
  }

  ProfileDetails = (profileData, index) => {
    const newData =
      profileData.consolidateddata &&
      profileData.consolidateddata.map((obj) => {
        return obj;
      });
    this.setState({ DataRows: newData });
  };

  componentDidMount() {
    data && data.forEach(this.ProfileDetails);
  }

  render() {
    console.log(this.state.DataRows);

    return (
      <div className="App">
        <h1>sample</h1>
      </div>
    );
  }
}

目前我只得到一个对象(第二行对象数组)在一个数组中,而不是3个对象。有谁能建议把3个物体组合成这样

[ { name: 'Paypal', expiry: '05/13/2023' },
{ name: 'phonepay', expiry: '05/19/2023' }, { name: 'Paytm', expiry: '05/25/2023' } ]

stackblitz链接https://stackblitz.com/edit/react-drpgcx?file=src%2FApp.js

2ledvvac

2ledvvac1#

你可以尝试在函数中使用reduce
比如

const getAllData = (data) => {
  return data.reduce((acc, val) => {
    const {consolidateddata} = val
    acc = acc.concat(...consolidateddata)
    return acc
  },[])
}
irlmq6kh

irlmq6kh2#

问题是您不了解ReactsetState工作原理和不变性

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataRows: [],
    };
  }

  setProfileDetails = () => {
    this.setState({ dataRows: data.reduce((acc, val) => {
      const {consolidateddata} = val
      acc = acc.concat(...consolidateddata)
      return acc
    },[]) });
  };

  componentDidMount() {
    this.setProfileDetails()
  }

  render() {
    return (
      <div className="App">
        <ol>
          {this.state.dataRows.map((d) => {
            return (
              <li key={d.expiry}>
                {`${d.name} - ${d.expiry}`}
              </li>
            )
          })}
        </ol>
      </div>
    );
  }
}

尝试学习这些概念之前

相关问题