Mixing 2 Array Objects Included Dictionary Object by Javascript

Gists

This is a sample script for combining and mixing 2 objects. Each object is an array which included a dictionary type. When the key of the dictionary object is the same, the values are mixed.

This can be also used for Google Apps Script.

Input

var obj1 = [
    {"key1": ["value1a1", "value1a2"]},
    {"key1": ["value1aa1", "value1aa2"]},
    {"key2": ["value2a1", "value2a2"]},
    {"key3": ["value3a1", "value3a2"]},
];
var obj2 = [
    {"key1": ["value1b1", "value1b2"]},
    {"key3": ["value3b1", "value3b2"]},
    {"key3": ["value3bb1", "value3bb2"]},
    {"key4": ["value4b1", "value4b2"]},
];

Output

[
    {"key1": ["value1a1", "value1a2", "value1b1", "value1b2", "value1aa1", "value1aa2"]},
    {"key2": ["value2a1", "value2a2"]},
    {"key3": ["value3a1", "value3a2", "value3b1", "value3b2", "value3bb1", "value3bb2"]},
    {"key4": ["value4b1", "value4b2"]}
]

Sample script :

Javascript :

function mixture(obj1, obj2) {
    Array.prototype.push.apply(obj1, obj2);
    var temp = [];
    var res = [];
    obj1.forEach(function(e, i){
        temp[i] = !~temp.indexOf(Object.keys(e)[0]) ? Object.keys(e)[0] : false;
        if (temp[i]) {
            res.push(e);
        } else {
            res.forEach(function(f, j){
                if (Object.keys(f)[0] == Object.keys(e)[0]) {
                    Array.prototype.push.apply(res[j][Object.keys(f)[0]], e[Object.keys(e)[0]]);
                }
            });
        }
    });
    return res;
}

var obj1 = [
    {"key1": ["value1a1", "value1a2"]},
    {"key1": ["value1aa1", "value1aa2"]},
    {"key2": ["value2a1", "value2a2"]},
    {"key3": ["value3a1", "value3a2"]},
];
var obj2 = [
    {"key1": ["value1b1", "value1b2"]},
    {"key3": ["value3b1", "value3b2"]},
    {"key3": ["value3bb1", "value3bb2"]},
    {"key4": ["value4b1", "value4b2"]},
];
var res = mixture(obj1, obj2);
console.log(JSON.stringify(res))

CoffeeScript :

This is a sample script for coffeescript.

Array.prototype.push.apply obj1, obj2
temp = []
res = []
for e, i in a
    temp[i] = if !~temp.indexOf Object.keys(e)[0] then Object.keys(e)[0] else false
    if temp[i]
        res.push e
    else
        for f, j in res
            if Object.keys(f)[0] is Object.keys(e)[0]
                Array.prototype.push.apply res[j][Object.keys(f)[0]], e[Object.keys(e)[0]]

 Share!