Here is one option:-
var array = [{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: ["val2", "val3"]
}, {
name: "foo2",
value: "val4"
}];
var output = [];
array.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.name == item.name;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].value = output[existingIndex].value.concat(item.value);
} else {
if (typeof item.value == 'string')
item.value = [item.value];
output.push(item);
}
});
console.dir(output);
Answer from BenG on Stack OverflowHere is one option:-
var array = [{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: ["val2", "val3"]
}, {
name: "foo2",
value: "val4"
}];
var output = [];
array.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.name == item.name;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].value = output[existingIndex].value.concat(item.value);
} else {
if (typeof item.value == 'string')
item.value = [item.value];
output.push(item);
}
});
console.dir(output);
Here is another way of achieving that goal:
var array = [{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: [
"val2",
"val3"
]
}, {
name: "foo2",
value: "val4"
}];
var output = array.reduce(function(o, cur) {
// Get the index of the key-value pair.
var occurs = o.reduce(function(n, item, i) {
return (item.name === cur.name) ? i : n;
}, -1);
// If the name is found,
if (occurs >= 0) {
// append the current value to its list of values.
o[occurs].value = o[occurs].value.concat(cur.value);
// Otherwise,
} else {
// add the current item to o (but make sure the value is an array).
var obj = {
name: cur.name,
value: [cur.value]
};
o = o.concat([obj]);
}
return o;
}, []);
console.log(output);
Best way to merge two objects on a matching key-value pair.
javascript - Merge object with same keys - Stack Overflow
javascript - How to merge two objects containing same keys but different values - Stack Overflow
How can I merge properties of two JavaScript objects? - Stack Overflow
Hey,
I'm having trouble making two objects into one on a matching key.
I have two objects coming from 2 apis and there is one matching key in the objects.
I want to iterate over them and if the storeId matches in both objects, I want to merge the two together as seen in the perfectObject.
I have tried the spread operator, Object.assign, for...in loop instead of the for loop seen here, but found close to none success.
Thanks for the help!
const logistics = [
{"logisticsId": "L5E69E26D8FCAE","storeId": 409388,"logisticsDate": "2020-03-12T07:19:09.000Z"
},]
const stores = [
{"storeId": 409388,"ka": 0,"country": "ru","name": "test","city": "Moscow","cxw": 1,"cx": 1,"plz": 22448
}]
const perfetObject = {
"storeId": 409388,"ka": 0,"country": "ru","name": "test","city": "Moscow","cxw": 1,"cx": 1,"plz": 22448,
"logisticsId": "L5E69E26D8FCAE","storeId": 409388,"logisticsDate": "2020-03-12T07:19:09.000Z"
}
let d = {}
for(let i = 0; i < logistics.length; ++i) {for (let k = 0; k < stores.length; ++k) {if(logistics.storeId === stores.storeId) {d = {
...stores .name,
...stores .city,
...logistics.logisticsId
}
}
}
}
console.log(d)
Reduce seems more useful in this case than forEach. Reduce will build a new thing from the input and return that.
const objectOne = [
{
one: null,
two: "Two",
three: null
}
];
const objectTwo = [
{
one: "One",
two: null,
three: "Three"
}
];
const merged = objectOne.map((item, idx) => {
return Object.entries(item).reduce((acc, [key, value]) => {
acc[key] = value === null && objectTwo.length > idx ? objectTwo[idx][key] : value;
return acc;
}, {})
});
console.log(merged);
Your mapping of keys/entries is pretty close. It might be easiest to do something like this though:
const objectOnes = [
{
one: null,
two: "Two",
three: null
},
{
a: 123,
b: undefined,
},
];
const objectTwos = [
{
one: "One",
two: null,
three: "Three"
},
{
b: 456,
}
];
function merge(a, b) {
const result = { ...a }; // copy a
for (const key in result) {
// Let's say we want to pick the non-null/undefined value
if (result[key] !== null && result[key] !== undefined) continue;
result[key] = b[key]; // copy from b
}
return result;
}
const merged = objectOnes.map((obj, i) => merge(obj, objectTwos[i]));
console.log(merged);
With Underscore.js, to merge an array of objects do:
var arrayOfObjects = [ {a:1}, {b:2, c:3}, {d:4} ];
_(arrayOfObjects).reduce(function(memo, o) { return _(memo).extend(o); });
It results in:
Object {a: 1, b: 2, c: 3, d: 4}
You should use lodash's defaultsDeep
_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
// → { 'user': { 'name': 'barney', 'age': 36 } }