skip to Main Content

I am having an array consists of 2 objects and each object again consists of an array of objects. I need to combine those inside array of objects.
please find the code below.

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

currently I am getting only one object(second row object array) in an array instead of 3 objects. can anybody suggest on this to get 3 combined objects like this

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

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

2

Answers


  1. you could try using reduce inside your function

    something like

    const getAllData = (data) => {
      return data.reduce((acc, val) => {
        const {consolidateddata} = val
        acc = acc.concat(...consolidateddata)
        return acc
      },[])
    }
    
    Login or Signup to reply.
  2. the problem is that you do not understand how react setState works and inmutability

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

    try to learn those concepts before

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search