Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active January 28, 2018 09:39
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Mixing 2 Array Objects Included Dictionary Object by Javascript

Mixing 2 Array Objects Included Dictionary Object by Javascript

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]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment