If I have two objects:
const obj1 = {
"1,1" : "hello",
}
and
const obj2 = {
"1,1" : "hi",
}
what would be the easiest way to merge them into:
obj3 = {
"1,1": ["hello", "hi"],
}
can i use the spread operator here? thanks!
If I have two objects:
const obj1 = {
"1,1" : "hello",
}
and
const obj2 = {
"1,1" : "hi",
}
what would be the easiest way to merge them into:
obj3 = {
"1,1": ["hello", "hi"],
}
can i use the spread operator here? thanks!
An alternative is using the function reduce
.
const obj1 = {"1,1" : "hello"},
obj2 = {"1,1" : "hi"},
obj3 = [obj1, obj2].reduce((a, c) => {
Object.keys(c).forEach(k => (a[k] || (a[k] = [])).push(c[k]));
return a;
}, {});
console.log(obj3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
a simple way to do this would be to use the internal for (.. in ...) of javascript : e.g.
obj1 = {1 : 2};
obj2 = {1 : 3};
obj3 = {};
for (element1 in obj1) {
for (element2 in obj2) {
if (element1 == element2) {
obj3[element1] = [];
obj3[element1].push(obj1[element1]);
obj3[element1].push(obj2[element2]);
}
}
}
//result : obj3 = {1 : [2,3]}
but then what if obj1 = {"1,1" : 2, 1.1 : 3} or obj1 = {"1,1" : [1,2,3,4]} ? You really need to "well define" your requirement, but this should be a pretty good start.
var obj1 = {
a: 1,
b: 2
};
var obj2 = {
a: 12,
c: 20
};
console.log(merge(obj1, obj2));
function merge(obj1, obj2) {
var obj3 = {};
Object.keys(obj1).forEach(function(key) {
pushIntoObj3(key, obj1[key]);
});
Object.keys(obj2).forEach(function(key) {
pushIntoObj3(key, obj2[key]);
});
function pushIntoObj3(key, val) {
if (!obj3[key]) {
obj3[key] = [];
}
obj3[key].push(val);
}
return obj3;
}
OUTPUT :
{
"a": [ 1, 12 ],
"b": [ 2 ],
"c": [ 20 ]
}