Reputation: 41
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"]
}];
Upvotes: 5
Views: 1626
Reputation: 92274
Here's a version using maps to avoid scanning for duplicates over and over. Also using some cool methods
It ended up being slightly smaller too.
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])
};
});
}
http://jsfiddle.net/mendesjuan/cD7uu/1/
Upvotes: 0
Reputation:
Too bad that we haven't seen any attempt.
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;
}
Usage :
var groups = merge([object1, object2, object3]);
Upvotes: 0
Reputation: 72857
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.
Upvotes: 6