how to merge objects in javascript without override values

arrays, javascript, javascript-objects, jquery

Solution

Here you go:

var object1 = {
    role: "os_and_type", 
    value: "windows"
};
var object2 = {
    role: "os_and_type", 
    value: "Android"
};
var object3 = {
    role: "features", 
    value: "GSM"
};

function convert_objects(){
    var output  = [];
    var temp    = [];
    for(var i = 0; i < arguments.length; i++){  // Loop through all passed arguments (Objects, in this case)
        var obj = arguments[i];                 // Save the current object to a temporary variable.
        if(obj.role && obj.value){              // If the object has a role and a value property
            if(temp.indexOf(obj.role) === -1){  // If the current object's role hasn't been seen before
                temp.push(obj.role);            // Save the index for the current role
                output.push({                   // push a new object to the output,
                    'role':obj.role,
                    'value':[obj.value]         //   but change the value from a string to a array.
                });
            }else{                              // If the current role has been seen before
                output[temp.indexOf(obj.role)].value.push(obj.value); // Save add the value to the array at the proper index
            }
        }
    }
    return output;
}

Call it like this:

convert_objects(object1, object2, object3);

You can add as many objects to the function as you'd like.

Problem

how can i merge duplicate key in objects and concat values in objects in one object i have objects like this ``` var object1 = { role: "os_and_type", value: "windows" }; var object2 = { role: "os_and_type", value: "Android" }; var object3 = { role: "features", value: "GSM" }; ``` how can i achieve this object ``` new_object = [{ role: "os_and_type", value: ["windows", "android"] }, { role: "features", value: ["GSM"] }]; ```

Original source