developer
developer

Reputation: 1687

Merge data using JavaScript

I would like to merge performance data using portfolio as base.

const data = {"portfolio": {"name": "portfolio 1","performance": [{"date": "2022-01-01","value": 100},{"date": "2022-01-15","value": 150}, {"date": "2022-02-01","value": 200}],"funds": [{"name": "fund 1","performance": [{"date": "2022-01-01","value": 3}, {"date": "2022-02-01","value": 4}],},{"name": "fund 2","performance": [{"date": "2022-01-01","value": 5}, {"date": "2022-02-01","value": 6}, {"date": "2022-03-01","value": 7}]}]}};

const {name, performance, funds} = data.portfolio;
const result = {
    headers: ["date", name, ... funds.map(({name}) => name)],
    data: funds[0].performance.map(({date, value}, i) => 
        [date, performance[i].value, ...funds.map(({performance: {[i]: {value}}}) => value)]
    )
};

console.log(result);

Current result:

{
  data: [["2022-01-01", 100, 3, 5], ["2022-02-01", 150, 4, 6]],
  headers: ["date", "portfolio 1", "fund 1", "fund 2"]
}

Expected result:

{
  headers: ["date", "portfolio 1", "fund 1", "fund 2"],
  data: [["2022-01-01", 100,3, 5], ["2020-01-15", 150, , ], ["2022-02-01", 200, 4, 6]]
}

Note that it does not include "2022-03-01" as portfolio does not have it.

JSFiddle: https://jsfiddle.net/mkdeveloper2021/o30nbf6j/9/

Upvotes: 0

Views: 55

Answers (1)

trincot
trincot

Reputation: 350781

As in this structure the performance arrays per fund do not necessarily have the same length as the global performance arrays, the matching entries do not occur at the same index, and must be explicitly matched by date.

In other words, the part that destructures a parameter with {[i]: {value}} needs to be replaced by a different solution. You'll have to find the right index. I suggest to use find for that:

const data = {"portfolio": {"name": "portfolio 1","performance": [{"date": "2022-01-01","value": 100}, {"date": "2022-01-15","value": 150}, {"date": "2022-02-01","value": 200}], "funds": [{"name": "fund 1","performance": [{"date": "2022-01-01","value": 3}, {"date": "2022-02-01","value": 4}],},{"name": "fund 2","performance": [{"date": "2022-01-01","value": 5}, {"date": "2022-02-01","value": 6}],}]}};

const {name, performance, funds} = data.portfolio;
const result = {
    headers: ["date", name, ...funds.map(({name}) => name)],
    data: performance.map(({date, value}, i) => 
        [date, value, ...funds.map(({performance}) => 
            performance.find(item => item.date == date)?.value
        )]
    )
};

console.log(result);

Upvotes: 2

Related Questions