如何在没有覆盖值的情况下合并javascript中的对象

har*_*man 5 javascript arrays jquery javascript-objects

我如何合并对象中的重复键和一个对象中的对象中的concat值我有这样的对象

var object1 = {
    role: "os_and_type", 
    value: "windows"
};
var object2 = {
    role: "os_and_type", 
    value: "Android"
};
var object3 = {
    role: "features", 
    value: "GSM"
};
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现这个目标

new_object = [{
    role: "os_and_type",
    value: ["windows", "android"]         
}, {
    role: "features",
    value: ["GSM"]
}];
Run Code Online (Sandbox Code Playgroud)

Cer*_*rus 6

干得好:

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;
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

convert_objects(object1, object2, object3);
Run Code Online (Sandbox Code Playgroud)

您可以根据需要向函数添加任意数量的对象.