Home > Blockchain >  Create single Array of Objects out of nested object array of objects
Create single Array of Objects out of nested object array of objects

Time:07-03

Details: {
  Expense: {
    2021:[
      {
        id: 1,
        name: first,
      },
      {
        1d: 2,
        name: second,
      },
    ],
    2022:[
      {
        id: 3,
        name: third,
      },
      {
        id: 4,
        name: fourth,
      },
    ],
  } 
}

I have a data something like this on the database and at initial stage I used it directly beacause of no reusability as:

const [expense, setExpense] = useState({});

Some api call...then(res => {
  setExpense(res.data[0].Details.Expense);
}

// This worked
return(
  <table>
    <thead>
      <tr>
        <th></th>'s ...        
      </tr>
    </thead>
    <tbody>
      {Object.keys(expense).map((key) => {
        return expense[key].map((data, index) => {
          return <tr>{data.values}</tr>'s...
        })
      })
    </tbody>
  </table>
)

The above map method worked perfectly as expected, but now I need to reuse the complete data so I want all the details as array of object so I did this:

const [dataArray, setDataArray] = useState();
const [expense, setExpense] = useState({});

Some api call...then(res => {
  setExpense(res.data[0].Details.Expense);
  setDataArray(
    Object.keys(res.data[0].Details.Expense).map((year) =>
      res.data[0].Details.Expense[year].map((data) => data)
    )
  );
  // Expected => [{...},{...},{...},{...}]
  // Getting nested array => [Array(2),Array(2)]
}

// This worked
return(
  <table>
    <thead>
      <tr>
        <th></th>'s ...        
      </tr>
    </thead>
    <tbody>
      {dataArray.map((data, index) => {
        return <tr>{data.values}</tr>'s...
        // Displays nothing
      })
    </tbody>
  </table>
)

the dataArray is showing as a nested array an I need is only a single array of objects

CodePudding user response:

Array.flat() will help you. --> MDN Docs: Array.prototype.flat()

const data = [
  [
    {
      id: 1,
      name: "first",
    },
    {
      id: 2,
      name: "second",
    },
  ],
  [
    {
      id: 3,
      name: "third",
    },
    {
      id: 4,
      name: "fourth",
    },
  ],
 ];

console.log('nested data array', data);
console.log('flat data array', data.flat());

  • Related