Hari Das Hari Das - 10 days ago 5
Node.js Question

Convert JavaScript object to array to be inserted into relational DB

I am using Nodejs. I need to store a JavaScript object in a relational database. Each key in the JavaScript object represents column name in DB. I have following:

var data = {
"aa": "99",
"bb": ["11","22"],
"cc": ["44","55","66"]
}


I want to convert this object into an array as follow:

data = [
{
"aa": "99",
"bb": "11",
"cc": "44"
},
{
"aa": "99",
"bb": "11",
"cc": "55"
},
{
"aa": "99",
"bb": "11",
"cc": "66"
},
{
"aa": "99",
"bb": "22",
"cc": "44"
},
{
"aa": "99",
"bb": "22",
"cc": "55"
},
{
"aa": "99",
"bb": "22",
"cc": "66"
}
]


Is there any way to do this ? I guess using recursive we can do it. But could not find any reference in Google.

Answer

You could use an iterative and recursive approach with a combination algorithm.

function combine(object) {
    function c(part, index) {
        array[index].forEach(function (a) {
            var p = part.concat(a);
            if (p.length === array.length) {
                result.push(p.reduce(function (r, b, i) {
                    r[keys[i]] = b;
                    return r;
                }, {}));
                return;
            }
            c(p, index + 1);
        });
    }

    var keys = Object.keys(object),
        array = keys.map(function (k) { return Array.isArray(object[k]) ? object[k] : [object[k]]; }),
        result = [];

    c([], 0);
    return result;
}

var data = { aa: "99", bb: ["11", "22"], cc: ["44", "55", "66"] },
    result = combine(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }