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
๐ŸŒ
GitHub
gist.github.com โ€บ sebysr โ€บ 6acada64a4b9d7ab21752ce6b81a8675
[Javascript] Merge objects with same key in array ยท GitHub
[Javascript] Merge objects with same key in array. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
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
๐ŸŒ
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)
๐ŸŒ
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
const arr = [{ "value": 10, "id": "111", "name": "BlackCat", }, { "value": 10, "id": "111", "name": "BlackCat", }, { "value": 15, "id": "777", "name": "WhiteCat", }]; const combinedItemsMap = (arr = []) => { const map = new Map(); arr.forEach(obj => { if (map.has(obj.id)) { map.get(obj.id).count++; } else { map.set(obj.id, {...obj, count: 1}); } }); return Array.from(map.values()); } console.log(combinedItemsMap(arr));
๐ŸŒ
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
๐ŸŒ
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.
Find elsewhere
Top answer
1 of 3
1

You're example includes invalid syntax for an array.

["topicName":"topic check check","topicName":"topic check popup"]

This could be an array of objects:

[{"topicName":"topic check check"},{"topicName":"topic check popup"}]

Or more likely (how my example is based):

topicName: ["topic check check", "topic check popup"]

Because it is not a one-to-one input to output, it is a good use of Array.prototype.reduce.

list.reduce((acc, row) => {
  const existingSel = acc.find(e => e.selectionId === row.selectionId);
  
  // If we don't have an entry, make one.
  if (!existingSel) {
    // Use expansion of row to avoid mutating source objects
    return [ ...acc, { ...row}];
  }
  
  if (Array.isArray(existingSel.topicName)) {
    // if the topicName is an array, add to it.
    existingSel.topicName.push(row.topicName);
  } else {
    // Otherwise, make it an array with the two options.
    existingSel.topicName = [existingSel.topicName, row.topicName];
  }
  return acc;
}, []);
2 of 3
0

You can use Array.reduce() to arrange the output according to selectionId. The output array contains objects each with a selectionId and topics array.

        
const input = [ { "selectionId":1, "topicName":"topic created or not validate" },{ "selectionId":1, "topicName":"hghhhg test test" },{ "selectionId":2, "topicName":"topic test" },{ "selectionId":3, "topicName":"new topic for test topic name and description name(test check)" },{ "selectionId":4, "topicName":"topic check check" },{ "selectionId":4, "topicName":"topic check popup" },{ "selectionId":5, "topicName":"test" } ]

const output = Object.values(input.reduce((acc, cur) => { 
    acc[cur.selectionId] = acc[cur.selectionId] || { selectionId: cur.selectionId, topics: []};
    acc[cur.selectionId].topics.push({ topicName: cur.topicName});
    return acc;
}, {}))

console.log('Output:', output); 
Run code snippetEdit code snippet Hide Results Copy to answer Expand

๐ŸŒ
30 Seconds of Code
30secondsofcode.org โ€บ home โ€บ javascript โ€บ object โ€บ merge objects
Merge two or more JavaScript objects - 30 seconds of code
March 20, 2024 - JavaScript arrays are fairly easy to merge, using the spread operator (...) or Array.prototype.concat(). Merging objects, however, is a little more complex, but can be done if you know the right techniques. 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.
๐ŸŒ
Atomizedobjects
atomizedobjects.com โ€บ blog โ€บ javascript โ€บ how-to-merge-two-objects-in-javascript
How to merge two objects in JavaScript | Atomized Objects
When you merge two objects with the same key in JavaScript you need to decide which one will take precedence in the merged array.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ merge-objects-in-array-with-similar-key-javascript
Merge objects in array with similar key JavaScript
August 21, 2020 - const arr = [ {id: 1, h1: 'Daily tests'}, {id: 2, h1: 'Details'}, {id: 1, h2: 'Daily classes'}, {id: 3, h2: 'Results'}, {id: 2, h3: 'Admissions'}, {id: 1, h4: 'Students'}, {id: 2, h5: 'Alumni'}, {id: 3, h3: 'Appreciations'}, {id: 1, h5: 'Tiny Tots'}, {id: 1, h6: 'Extras'}, ]; const clubArray = (arr) => { return arr.reduce((acc, val, ind) => { const index = acc.findIndex(el => el.id === val.id); if(index !== -1){ const key = Object.keys(val)[1]; acc[index][key] = val[key]; } else { acc.push(val); }; return acc; }, []); }; console.log(clubArray(arr));
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