0
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

1
  • 1
    No need to map the Object.keys, you can just retrieve the Object.values directly Object.values(res.data[0].Details.Expense).flat() Commented Jul 2, 2022 at 21:19

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.