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

标签 javascript jquery arrays javascript-objects

如何将对象中的重复键合并到一个对象中并连接对象中的值 我有这样的对象

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

我怎样才能实现这个目标

new_object = [{
    role: "os_and_type",
    value: ["windows", "android"]         
}, {
    role: "features",
    value: ["GSM"]
}];

最佳答案

给你:

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;
}

这样调用它:

convert_objects(object1, object2, object3);

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

关于javascript - 如何在不覆盖值的情况下合并javascript中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21495610/

相关文章:

Javascript 将元素从另一个对象添加到一个对象

javascript - 在 Html 应用程序中,使用 javascript,如何获取图像在屏幕上的位置并将其放入文本文档中?

javascript - 表单验证问题。 Javascript/HTML

javascript - 如何使用 jQuery 将 JSON 数据推送到数组中?

c++ - 错误 C2229 : class 'VectorRemake<T>' has an illegal zero-sized array

java - 打印数组

javascript - 更改样式表javascript

javascript - 在 react.js 中加载页面后从 googleapis 加载字体

javascript - 根据属性值 jquery 重新排列选择 optgroup 标签

javascript - Div 不知道屏幕大小调整