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
How to Make New Line or Break in Array
Creating a Json Dynamically With Each Input Value Using Jquery
How to Insert Dashes Between Each Two Even Digits of a Specific Number
React-Router Urls Don't Work When Refreshing or Writing Manually
Check If a String Has White Space
Stylesheet Not Loading Because Mime Type Is Text/Html
How to Trigger Change of Option in Dropdown When Options Can Have Same Value
Reactjs and Images in Public Folder
How to Convert All Elements in an Array to Integer in JavaScript
How to Open Specific Web Browsers Using Hyperlinks
How to Correctly Use Axios Params With Arrays
Break the Loop of an Array Looping Function (Map, Foreach, etc.)
Jquery Validation Code for Not Allowed Only Blank Space in Textbox
How to Clear Browsing History Using JavaScript
How to Remove Special Character from Json Without Parsing
Trigger Event When Element Becomes Visible With Ngif
How to Pass Array Variable from View to Controller in Spring MVC