Home > Net >  Javascript combine 2 map arrays
Javascript combine 2 map arrays

Time:09-17

I've got a question about 2 arrays I have. I've been mapping one array into a table. First array looks like this:

enter image description here

{data.portfolioHoldings.map((portfolioholding) => (
      <tbody key={portfolioholding.id}>
        <tr key={portfolioholding.id}>
          <th scope="row">{portfolioholding.id}</th>
          <td>{portfolioholding.ticker_symbol}</td>
          <td>{portfolioholding.amount}</td>
          <td>{portfolioholding.fees}</td>))}

Which results in a table like this: enter image description here

However I've got another array (from a different api source):

enter image description here

I'd like to combine these 2 data sources into 1 table . As you can see ID 1 of the second array is 149.03. I'd like to have another < td> behind "fees" that says latest price with the value of ID 1.

How can I map both arrays and work together like one?

Thank you in advance!!!

CodePudding user response:

If I understand your question correctly, let's say your second array is named arr2, you can do this:

{data.portfolioHoldings.map((portfolioholding, index) => (
      <tbody key={portfolioholding.id}>
        <tr key={portfolioholding.id}>
          <th scope="row">{portfolioholding.id}</th>
          <td>{portfolioholding.ticker_symbol}</td>
          <td>{portfolioholding.amount}</td>
          <td>{portfolioholding.fees}</td>))
          <td>{arr2[index].quote.latestPrice}</td>))
}

Make sure two arrays have the same length and the second array should always have quote.latestPrice inside each element, otherwise, you will encounter errors.

Just a note, seems like your tbody should be outside of the map function, only one tbody is needed for each table

CodePudding user response:

Merged data, something like this ?

let data1 = [
    { id: "1", name: "AAPL", amount: 154, fees: 0.5 },
    { id: "1", name: "AMZN", amount: 3000, fees: 0.5 },
];

let data2 = [
    { id: "1", lastePrice: 149.55 },
    { id: "2", lastePrice: 3475.79 }
];

const allData = (d1, d2) =>
    d1.map(item1 => ({
        ...d2.find((item2) => (item2.id === item1.id) && item2),
        ...item1
    }));

console.log( allData(data1, data2));

  • Related