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 Overflow
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › merge objects
Merge two or more JavaScript objects - 30 seconds of code
March 20, 2024 - const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const merged = { ...obj1, ...obj2 }; // { a: 1, b: 3, c: 4 } const merged2 = Object.assign({}, obj2, obj1); // { b: 2, c: 4, a: 1 } Instead of overwriting properties with the same key, we usually want to combine their values.
Discussions

Best way to merge two objects on a matching key-value pair.
Well in your example, you are attempting to combine two arrays of objects into an object, which assumes that the arrays each contain exactly one object that share a store ID. We can allow for multiple logistics and stores by aiming for an array of combined objects: const storesByStoreId = stores.reduce( (obj, store) => { if (!obj.hasOwnProperty(store.storeId)) { obj[store.storeId] = store; } return obj; }, {} ); const perfectArray = logistics.map(logistic => ({ ...storesByStoreId[logistic.storeId], ...logistic })); The result will look like this: [ { storeId: 409388, ka: 0, country: 'ru', name: 'test', city: 'Moscow', cxw: 1, cx: 1, plz: 22448, logisticsId: 'L5E69E26D8FCAE', logisticsDate: '2020-03-12T07:19:09.000Z' } ] And you can reference that first and only object with perfectArray[0]. More on reddit.com
🌐 r/learnjavascript
2
3
September 15, 2021
javascript - Merge object with same keys - Stack Overflow
Considering you have instead two objects with same keys you can make two types of merge: shallow or deep. More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to merge two objects containing same keys but different values - Stack Overflow
I'm wanting to merge two array that carry objects with the same keys, but one object may have a value, but the other object, carrying the same key, may have a null value. I'm wanting to merge the ... More on stackoverflow.com
🌐 stackoverflow.com
How can I merge properties of two JavaScript objects? - Stack Overflow
ES2018/TypeScript: Many answers ... to merge two objects without overwriting overlapping object keys. My function also accepts unlimited number of objects to merge as function arguments: (I'm using TypeScript notation here, feel free to delete the :object[] type in the function argument if you're using plain JavaScript)... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › How-do-you-merge-two-objects-and-sum-the-values-of-the-same-key-in-JavaScript
How to merge two objects and sum the values of the same key in JavaScript - Quora
Answer: There is usually more than one way to solve a problem in programming. I’m assuming you’re asking this because of a practice problem you encountered either at school or during your own self-learning journey, so instead of simply writing some code for you and leaving it at that, let’s ...
🌐
Atomizedobjects
atomizedobjects.com › blog › javascript › how-to-merge-two-objects-in-javascript
How to merge two objects in JavaScript | Atomized Objects
The one you want to key with the same key must be last in the merging of the two objects with the same key.
🌐
DEV Community
dev.to › pragyes31 › how-to-merge-js-objects-with-common-keys-45i3
How to merge JS objects with common keys - DEV Community
June 16, 2021 - If the key is present in both the objects, then we will add the values of the two and store it in originalObject. If not, we will create a new key in the originalObject object.
🌐
TutorialsPoint
tutorialspoint.com › article › javascript-program-to-merge-two-objects-into-a-single-object-and-adds-the-values-for-same-keys
JavaScript program to merge two objects into a single object and adds the values for same keys
This has to be done in linear time and constant space, means using at most only one loop and merging the properties in the pre-existing objects and not creating any new variable. ... const obj1 = { value1: 45, value2: 33, value3: 41, value4: 4, value5: 65, value6: 5, value7: 15, }; const obj2 = { value1: 34, value3: 71, value5: 17, value7: 1, value9: 9, value11: 11, }; const mergeObjects = (obj1, obj2) => { for(key in obj1){ if(obj2[key]){ obj1[key] += obj2[key]; }; }; for(key in obj2){ if(!obj1[key]){ obj1[key] = obj2[key]; }; }; return obj1; }; mergeObjects(obj1, obj2); console.log(obj1);
Find elsewhere
🌐
Reddit
reddit.com › r/learnjavascript › best way to merge two objects on a matching key-value pair.
r/learnjavascript on Reddit: Best way to merge two objects on a matching key-value pair.
September 15, 2021 -

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)

🌐
TutorialsPoint
tutorialspoint.com › article › merge-javascript-objects-with-the-same-key-value-and-count-them
Merge JavaScript objects with the same key value and count them
Method 1: Using reduce() to build an accumulator array, checking if an object with the same ID already exists · Method 2: Using a Map to store unique objects by ID as keys, making lookups faster · The Map approach is more efficient for large ...
🌐
SitePoint
sitepoint.com › blog › javascript › how to merge objects in javascript
How to Merge Objects in JavaScript — SitePoint
November 5, 2024 - The spread operator (...) is a common approach to merge objects in JavaScript. It has the form {...object1, ...object2}. When properties with the same keys exist in the source objects, the spread operator overwrites the values in the target object with the latest source object’s values.
🌐
YouTube
youtube.com › watch
Merge two objects with matching keys | Javascript Challenger #12 - YouTube
#mukundprogrammingtutorials #CreatingForIndia #jsproblems==================================Join this channel to get access to perks:https://www.youtube.com/c...
Published: May 18, 2022
🌐
Scaler
scaler.com › home › topics › javascript merge objects
JavaScript Merge Objects - Scaler Topics
May 4, 2023 - Whereas Deep Merging also checks for nested values while overwriting and only replaces the conflicting values. We can also create our own function to merge two objects in JavaScript. Along with all these, we can also use Jquery's $.extend() method and the _.merge() method in JavaScript to merge ...
🌐
DEV Community
dev.to › ratracegrad › how-to-merge-objects-in-javascript-106p
How to Merge Objects in JavaScript - DEV Community
January 13, 2023 - It is possible that the source and target objects have a key that are the same. In that case, the source object value overwrites the value in the target object. ... const target = { name: 'Jennifer', age: 60, 'city': 'Atlanta' }; const source ...
🌐
Stack Overflow
stackoverflow.com › questions › 72492498 › merge-object-with-same-keys
javascript - Merge object with same keys - Stack Overflow
If a shallow merge is sufficient, you can use Object.assign to do the job like the following, but iterating for each key: obj3.foo1 = Object.assign({}, obj1.foo1, obj2.foo1); For shallow copies, keep in mind that the references are maintained since Object.assign only copies the values as explained into the documentation which can be a problem for nested objects. But if you need a deep merge it would be a little bit more tricky. The easiest way I guess is using a library like deepmerge-json: ... This will make a deep merge between the two objects creating a third one with no reference to the original ones.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › combine object arrays
Combine 2 JavaScript object arrays based on a key - 30 seconds of code
March 26, 2024 - For each value in the arrays, you can check if the object has the specified key. If it does, you can add it to the accumulator object, combining it with any existing object that has the same key.
🌐
Medium
allaboutcode.medium.com › 3-ways-to-merge-2-json-objects-with-the-same-key-in-javascript-82734fc7807d
3 ways to merge 2 JSON objects with the same key in JavaScript | by Marika Lam | Medium
September 21, 2022 - 3 ways to merge 2 JSON objects with the same key in JavaScript The 3 ways to merge 2 JSON objects are Nested for loop Map and Object.assign concat() 1. Nested for loop
🌐
W3docs
w3docs.com › javascript
How to Merge Properties of Two JavaScript Objects Dynamically
In such a scenario, it is required to use the value of the key of the object appearing later in the distribution. ... let obj1 = { name: "W3Docs", }; let obj2 = { name: "Javascript" }; let Sites = { ...obj1, ...obj2 }; console.log(Sites) ... As an alternative solution, you can use the Object.assign() method. As a rule, this method is applied for copying the values of all properties from a single and more source objects to a target object.
🌐
GitHub
gist.github.com › sebysr › 6acada64a4b9d7ab21752ce6b81a8675
[Javascript] Merge objects with same key in array · GitHub
[Javascript] Merge objects with same key in array · Raw · MergeObjectIntoArray.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.