Got very interesting code in the answers. I would like to mention that I also could achieve the result using the lodash method .merge().

const result = _.merge(listOfQuestions, listOfAnswers)

const listOfQuestions = [{question1:{important: true}}, {question2:{important: false}}]
const listOfAnswers = [{question1:{answer: false}}, {question2:{answer: true}}]

const result = _.merge(listOfQuestions, listOfAnswers)
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from Phoenix on Stack Overflow
🌐
EyeHunts
tutorial.eyehunts.com › home › merge javascript objects in array with same key es6 | example code
Merge JavaScript objects in array with same key es6 | Example code
September 16, 2022 - <!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script> </head> <body> <script> const listOfQuestions = [{ question1: { important: true } }, { question2: { important: false } }]; const listOfAnswers = [{ question1: { answer: false } }, { question2: { answer: true } }]; const result = _.merge(listOfQuestions, listOfAnswers) console.log(result) </script> </body> </html> ... var arr = [ { "abc": [ { "name": "test", "addr": "123", } ] }, { "def": [ { "first_name": "test", "last_name": "test" } ] }, { "def": [ { "first_name": "test1", "last_name": "test1" } ] }] const result = arr.reduce((acc, curr) => { const key = Object.keys(curr)[0] const found = acc.find(i => i[key]) if (!found) { acc.push(curr) } else { found[key] = [ ...found[key], ...curr[key] ] } return acc; }, []) console.log(result)
Discussions

Merge JavaScript objects in array with same key - Stack Overflow
What is the best way to merge array contents from JavaScript objects sharing a key in common? How can array in the example below be reorganized into output? Here, all value keys (whether an array o... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Merge 2 object with same key, value from 2 array - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Turn scattered docs and code into trusted AI context. Explore the new Stack Internal platform More on stackoverflow.com
🌐 stackoverflow.com
September 23, 2017
arrays - ES6 / JavaScript - How to merge an object on a specific key - Stack Overflow
I'm trying to merge an object on a specific key (field is the key) but can't seem to find a way to do it. The images will better illustrate my problem. What I'm trying to get is this... 0: {field: " More on stackoverflow.com
🌐 stackoverflow.com
June 26, 2018
Combining the content of multiple objects that have the same key with that key as the property in JavaScript - Stack Overflow
When merging property values other than arrays and objects how does one handle it (e.g. summing up number values? string/array concatenation? Or collecting/pushing them in/to arrays?). How are array values going to be handled? ... You can iterate over the object keys and create a new object out of their aggregation. You can use ES6 ... More on stackoverflow.com
🌐 stackoverflow.com
May 31, 2022
People also ask

What does the learnwithparam blog cover?
The blog covers production AI engineering, with a tilt toward RAG, agentic systems, and the operational layer that turns demos into services. New posts ship roughly daily and lean on patterns the mentors actually use at work, not the framework-of-the-week. Every post includes a working code snippet, a mermaid diagram, and a Monday-morning checklist you can act on.
🌐
learnwithparam.com
learnwithparam.com › home › blog
AI Engineering Blog - Tutorials, Guides & Best Practices | ...
How do I follow new posts?
Subscribe to the newsletter (signup form on every post page) to get new posts in your inbox. The blog also publishes an RSS feed at /rss.xml. For social, follow Param on Twitter and LinkedIn. Posts are tagged by category so you can filter for RAG, agents, tooling, or whichever topic matters to you.
🌐
learnwithparam.com
learnwithparam.com › home › blog
AI Engineering Blog - Tutorials, Guides & Best Practices | ...
How often are new posts published?
A new post lands roughly every day. The cadence is intentional: small, high-signal posts that solve one specific production problem each, instead of an occasional 5000-word omnibus. If you want every post in your inbox, the newsletter signup is at the bottom of every post page.
🌐
learnwithparam.com
learnwithparam.com › home › blog
AI Engineering Blog - Tutorials, Guides & Best Practices | ...
🌐
Reactgo
reactgo.com › javascript-merge-array-objects-key
JavaScript merge array of objects by key (es6) | Reactgo
July 24, 2023 - function mergeArrayObjects(arr1,arr2){ let start = 0; let merge = []; while(start < arr1.length){ if(arr1[start].id === arr2[start].id){ //pushing the merged objects into array merge.push({...arr1[start],...arr2[start]}) } //incrementing start value start = start+1 } return merge; } ... How to exit the JavaScript functionHistory of JavaScriptHow to combine two arrays in JavaScriptHow to convert String to Date in JavaScriptHow to Solve date.getDay is not a Function in JavaScriptHow to get number of keys in JavaScript object
🌐
SitePoint
sitepoint.com › blog › javascript › how to merge objects in javascript
How to Merge Objects in JavaScript — SitePoint
November 5, 2024 - When merging objects with properties that have the same keys, both the spread operator and Object.assign() overwrite the values in the resulting object with values from the latest source object. This behavior may cause the loss of data if not handled carefully. The spread operator is part of ECMAScript 2015 (ES6) and is not supported in older JavaScript environments or browsers, such as Internet Explorer.
🌐
Atomizedobjects
atomizedobjects.com › blog › javascript › how-to-merge-two-objects-in-javascript
How to merge two objects in JavaScript | Atomized Objects
This post is going to go over ... overwriting and more. Let’s get started. The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator (...)....
Find elsewhere
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › merge objects
Merge two or more JavaScript objects - 30 seconds of code
March 20, 2024 - Both the spread operator (...) and Object.assign() can be used to merge two or more objects into a single object. However, these methods only perform a shallow merge, meaning that nested objects are not merged. They also have the drawback of overwriting properties with the same key.
🌐
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
medium.com › swlh › merging-javascript-objects-b89af94d5b59
Merging JavaScript Objects. A short guide to creating a new object… | by Michael McShinsky | The Startup | Medium
February 22, 2021 - The spread operator was introduced with ES6 and allows us to merge multiple arguments or objects and returns a new combined value anywhere defined in your code. If any of the objects or values added to the spread operation share the same property ...
🌐
learnwithparam
learnwithparam.com › home › blog
AI Engineering Blog - Tutorials, Guides & Best Practices | learnwithparam
August 13, 2019 - Technical deep-dives on AI agents, RAG pipelines, prompt engineering, system design, and production LLM systems.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript merge objects
How to Merge Objects in JavaScript
March 29, 2020 - After merging, the person and employee ... string keyed properties of source objects to a target object, you can use the Lodash ._merge() method:...
🌐
javaspring
javaspring.net › blog › how-do-i-merge-two-javascript-objects-together-in-es6
How to Merge Two JavaScript Objects in ES6+? Built-in Methods, Alternatives & Why No Native Extend? — javaspring.net
Object merging is the process of combining properties from two or more source objects into a single target object. By default, if multiple source objects have properties with the same key, the last source object’s value overwrites earlier ones.
🌐
DEV Community
dev.to › ratracegrad › how-to-merge-objects-in-javascript-106p
How to Merge Objects in JavaScript - DEV Community
January 13, 2023 - ... const target = { name: 'Jennifer', ...g(target); // { name: 'Anne', age: 60, city: 'Athens', state: 'GA', country: 'USA' } The spread operator was introduced in ES6....
Top answer
1 of 2
1

Here the solution using lodash and uniqWith function: JSFiddle.

Here's the code:

function merge(array) {
  return _.uniqWith(array, compareAndMerge)
}

function compareAndMerge(first, second) {
    if (first.field === second.field) {
        first.values = second.values = [].concat(first.values, second.values)
        return true
    }
    return false
}


var data = [{
  field: 'Currency',
  operator: 'IN',
  values: ['usd']
}, {
  field: 'Currency',
  operator: 'IN',
  values: ['gbp']
}, {
  field: 'Amount',
  operator: 'IN',
  values: [2]
},
{
  field: 'Amount',
  operator: 'IN',
  values: [3]
}]

console.log(merge(data))

Lodash.uniqWidth function wants an array and a comparator. In case of equal fields we edit values of the two compared elements assigning the concatenation of the two values arrays.

Something more: it's a transgression to edit objects inside the comparator, but I think that it could run safely.

2 of 2
0

Sounds like you are looking to combine concepts of merging objects and concatenating arrays along the way.

Using vanilla ES6 (probably far from optimal in terms of performance):

const one = {field: "currency", values: ["USD"]};
const two = {field: "currency", values: ["GBP"]};

const mergeConcat = (obj1, obj2) => {
  const result = {...obj1, ...obj2};
  Object.keys(obj1).map(key => {
    if (Object.keys(obj2).includes(key) && Array.isArray(obj1[key])) {
      result[key] = obj1[key].concat(obj2[key]);
    }
  })
  return result;
}

console.log(mergeConcat(one, two))
// { field: 'currency', values: [ 'USD', 'GBP' ] }
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Using lodash (almost directly from their docs):

const customizer = (objValue, srcValue) => {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
}

const one = {field: "currency", values: ["USD"]};
const two = {field: "currency", values: ["GBP"]};

console.log(_.mergeWith(one, two, customizer))
// { field: 'currency', values: [ 'USD', 'GBP' ] }
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
Dirask
dirask.com › posts › JavaScript-merge-objects-in-array-with-the-same-keys-DKgNRD
JavaScript - merge objects in array with the same keys
// ONLINE-RUNNER:browser; const array = [ { type: 1, values: 'a' }, { type: 1, values: ['b', 'c'] }, { type: 2, values: 'd' } ]; const result = []; array.forEach((object) => { const existing = result.filter((item) => item.type == object.type); if (existing.length) { const existingIndex = result.indexOf(existing[0]); result[existingIndex].values = result[existingIndex].values.concat(object.values); } else { if (typeof object.values == 'string') object.values = [object.values]; result.push(object); } }); console.log(JSON.stringify(result)); ... If you want values to be an array of numbers instead of strings, just change the condition in line 15 from 'string' to 'number' type. JavaScript - group / grouping array items with reduce method
🌐
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.
Top answer
1 of 1
2

You can use reduce for that and iterate over the object keys of each object:

const res = array.reduce((a, b) => {
    Object.keys(b).forEach(k => {
        a[k] = (a[k] || 0) + b[k];
    });
    return a;
}, Object.create(null));

console.log(res);
<script>
const array = [
    {
        RT: 0.3396966806905289,
        Real: 0.03721461991442617,
        fired: 0.26138293747172237,
        'Real Madrid': 0.15767570563383954,
        Madrid: 0.2771992640023346,
        Zidane: 0.3218878635800967,
        'Florentino Perez': 0.31535141126767907,
        leave: 0.1632670522868711,
        manager: 0.12690962022792524,
        tancredipalmeri: 0.3218878635800967,
        Perez: 0.4543985280046692,
        Florentino: 0.44189852800466917
    },
    {
        Cannavaro: 0.2709492640023346,
        Ashley: 0.2771992640023346,
        'Ashley Cole': 0.15767570563383954,
        Casillas: 0.3896966806905289,
        Ronaldo: 0.22094926400233458,
        Zidane: 0.22094926400233458,
        Messi: 0.22094926400233458,
        Lampard: 0.22094926400233458,
        Iniesta: 0.22094926400233458,
        Terry: 0.2771992640023346,
        Henry: 0.19890866571173632,
        Cole: 0.22094926400233458,
        Ivanovic: 0.3218878635800967
    },
    {
        RT: 0.3396966806905289,
        effleurer: 0.22094926400233458,
        'n\'a': 0.2709492640023346,
        top: 0.13189246756926315,
        Zidane: 0.2709492640023346,
        entraineur: 0.22094926400233458,
        monde: 0.22094926400233458,
        au: 0.2271992640023346,
        'au monde': 0.20434237230050623,
        Mvssi10: 0.3218878635800967,
        JAMAIS: 0.2709492640023346
    },
    {
        RT: 0.3396966806905289,
        Real: 0.10790900513119943,
        FrenchRMCF: 0.3218878635800967,
        en: 0.2271992640023346,
        histoire: 0.2709492640023346,
        coach: 0.2271992640023346,
        au: 0.2271992640023346,
        Zidane: 0.22094926400233458,
        'en tant': 0.15767570563383954,
        tant: 0.22094926400233458
    }
]
</script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand