Giorgian Giorgian - 3 years ago 100
Javascript Question

How to change object structure

I want to change the structure of my JavaScript object to another. My problem is that for each object, I have to create up to three different objects:

My input:

[
{date: "21-05", cash: "500", card: "200", points: "100"},
{date: "26-05", card: "100", points: "50"}
]


Desired output:

[
{date: "21-05", amount: "500", paymentType: cash },
{date: "21-05", amount: "200", paymentType: card },
{date: "21-05", amount: "200", paymentType: points },
{date: "26-05", amount: "100", paymentType: card },
{date: "26-05", amount: "50", paymentType: points }
]


cash, card, point are global
const

Answer Source

You could iterate the array and the keys and check if not date, then build a new object with the data. Collect until all objects are visited.

var data = [{ date: "21-05", cash: "500", card: "200", points: "100" }, { date: "26-05", card: "100", points: "50" }],
    result = data.reduce(function (r, o) {
        Object.keys(o).forEach(function (k) {
            if (k !== 'date') {
                r.push({ date: o.date, amount: o[k], paymentType: k });
            }
        });
        return r;
    }, []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download