[SOLVED] Transform object using TypeScript / Javascript

Issue

I have the following object in Typescript / Javascript:

{
    "portfolio": {
        "name": "portfolio 1",
        "performance": [{"date": "2022-01-01","value": 1}, {"date": "2022-02-01","value": 2}],
        "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}],
            }
        ]
    }
}

How can I transform it to the following format:

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

Solution

It seems you want to transpose the inner structure of the input object.

Here is how you can make it happen:

const data = {"portfolio": {"name": "portfolio 1","performance": [{"date": "2022-01-01","value": 1}, {"date": "2022-02-01","value": 2}],"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: {[i]: {value}}}) => value)]
    )
};

console.log(result);

Note that some of the output data is numeric. I suppose that is more useful that the strings you have listed in your desired output. If you really want strings, then just convert them by doing performance[i].value+"" and => value+"".

Answered By – trincot

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *