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"]
}];
JavaScript Merge Objects To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.
Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones. The Object. assign() method only copies enumerable and own properties from a source object to a target object.
concat is the proper way to merge 2 arrays into one.
Deep merging ensures that all levels of the objects we merge into another object are copied instead of referencing the original objects. In this article, we'll look at how to deep merge JavaScript objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With