如何合并对象中的重复键和一个对象中对象的concat值 我有像这样的对象
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"]
}];
答案 0 :(得分: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;
}
这样称呼:
convert_objects(object1, object2, object3);
您可以根据需要为函数添加任意数量的对象。
答案 1 :(得分:0)
太糟糕了,我们还没有看到任何尝试。
function merge(array) {
var temp = {},
groups = [],
l = array.length,
i = 0,
item;
while (item = array[i++]) {
if (!temp[item.role]) {
temp[item.role] = {
role: item.role,
value: [item.value]
};
} else if (temp[item.role].value.indexOf(item.value) === -1) {
temp[item.role].value.push(item.value);
}
}
for (var k in temp) {
groups.push(temp[k]);
}
return groups;
}
用法:
var groups = merge([object1, object2, object3]);
答案 2 :(得分:0)
这是一个使用地图的版本,以避免反复扫描重复项。还使用一些很酷的方法
它最终也略微变小了。
function merge(objects) {
var roles = {};
objects.forEach(function(obj){
roles[obj.role] = roles[obj.role] || {};
roles[obj.role][obj.value] = {};
});
return Object.keys(roles).map(function(role){
return {
role: role,
value: Object.keys(roles[role])
};
});
}