Вы можете использовать комбинацию map
и filter
.
portfolios.map (pf => ({...pf, positions: positions.filter (({portfolioId}) => pf.id == portfolioId)}))
. Или обобщить эту идею и использовать помощника для объединения ваших массивов.
function join (left, right, {joinKey,foreignKey, idKey='id'}) {
return left.map (lI => ({...lI,[joinKey]: right.filter (rI => lI[idKey] == rI[foreignKey])}))
}
let joined = join (portfolios, positions, {joinKey: 'positions', foreignKey: 'portfolioId'})
console.log (joined)
<script>
const portfolios = [
{
id: 1,
name: "Investor 1"
},
{
id: 2,
name: "Investor 2"
},
];
const positions = [
{
id: 1,
portfolioId: 1,
currency: "GBP",
value: -2.02,
date: "2018-06-07"
},
{
id: 2,
portfolioId: 1,
currency: "EUR",
value: 1906302.15,
date: "2018-06-07"
},
{
id: 3,
portfolioId: 2,
currency: "GBP",
value: 1379804.1,
date: "2018-06-07"
},
{
id: 4,
portfolioId: 2,
currency: "CAD",
value: 2401938.18,
date: "2018-06-07"
}
];
</script>