How to Merge an Array of Objects With Same Keys in Es6 JavaScript

How can I merge an array of Objects with same keys in ES6 javascript?

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>

Merge objects with same key in array of objects in javascript

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)

ES6 / JavaScript - How to merge an object on a specific key

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.

merge objects in same array based on common value in Javascript

You can use lodash#groupBy to group all items in the array by id and then use lodash#map with an iteratee of lodash#assign that is wrapped with a lodash#spread to make the array callback as a list of arguments for lodash#assgin.

var result = _(array)
.groupBy('id')
.map(_.spread(_.assign))
.value();

var array = [  {    assignmentId:17,    email:"john.smith@email.com",    expectation: "Make sure to proofread!",    firstName:"John",    id:23,    ignoreForFeedback: true,    lastName:"Smith",    level:2,    levelFraction:null,    score:35  },  {    assignmentId:17,    countsPerCategory: Array(4),    email:"john.smith@email.com",    firstName:"John",    frequentErrors: Array(5),    id:23,    ignoreForGrading: true,    lastName:"Smith"  },  {    assignmentId:17,    email:"cl@email.com",    expectation: "cite sources",    firstName:"Cindy",    id:45,    ignoreForFeedback: true,    lastName:"Lee",    level:2,    levelFraction:null,    score:32  },  {    assignmentId:17,    countsPerCategory: Array(4),    email:"cl@email.com",    firstName:"Cindy",    frequentErrors: Array(5),    id:45,    ignoreForGrading: true,    lastName:"Lee"  }];
var result = _(array) .groupBy('id') .map(_.spread(_.assign)) .value(); console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


Related Topics



Leave a reply



Submit