We can use the spread operator on arrays within an array literal( [] ) to merge them. Let's see it with an example. First, we will take two arrays, arr1 and arr2 . Then merge the arrays using the spread operator( ... ) within an array literal.
Use the spread syntax (...) to merge arrays in React, e.g. const arr3 = [...arr1, ...arr2] . The spread syntax is used to unpack the values of two or more arrays into a new array. The same approach can be used to merge two or more arrays when setting the state.
To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.
If you want to merge 2 arrays of objects in JavaScript. You can use this one line trick
Array.prototype.push.apply(arr1,arr2);
For Example
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
Array.prototype.push.apply(arr1,arr2);
console.log(arr1); // final merged result will be in arr1
Output:
[{"name":"lang","value":"English"},
{"name":"age","value":"18"},
{"name":"childs","value":"5"},
{"name":"lang","value":"German"}]
With ES6 you can do it very easy as below:
var arr1 = new Array({name: "lang", value: "German"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var arr3 = [...arr1, ...arr2];
Output:
arr3 = [
{"name":"lang","value":"German"},
{"name":"age","value":"18"},
{"name":"childs","value":"5"},
{"name":"lang","value":"German"}
]
For those who are experimenting with modern things:
var odd = [{
name: "1",
arr: "in odd"
},
{
name: "3",
arr: "in odd"
}
];
var even = [{
name: "1",
arr: "in even"
},
{
name: "2",
arr: "in even"
},
{
name: "4",
arr: "in even"
}
];
// ----
// ES5 using Array.filter and Array.find
function merge(a, b, prop) {
var reduced = a.filter(function(aitem) {
return !b.find(function(bitem) {
return aitem[prop] === bitem[prop];
});
});
return reduced.concat(b);
}
console.log("ES5", merge(odd, even, "name"));
// ----
// ES6 arrow functions
function merge(a, b, prop) {
var reduced = a.filter(aitem => !b.find(bitem => aitem[prop] === bitem[prop]))
return reduced.concat(b);
}
console.log("ES6", merge(odd, even, "name"));
// ----
// ES6 one-liner
var merge = (a, b, p) => a.filter(aa => !b.find(bb => aa[p] === bb[p])).concat(b);
console.log("ES6 one-liner", merge(odd, even, "name"));
// Results
// ( stuff in the "b" array replaces things in the "a" array )
// [
// {
// "name": "3",
// "arr": "in odd"
// },
// {
// "name": "1",
// "arr": "in even"
// },
// {
// "name": "2",
// "arr": "in even"
// },
// {
// "name": "4",
// "arr": "in even"
// }
// ]
// for posterity, here's the old skool version
function merge(a, b, prop) {
var reduced = [];
for (var i = 0; i < a.length; i++) {
var aitem = a[i];
var found = false;
for (var ii = 0; ii < b.length; ii++) {
if (aitem[prop] === b[ii][prop]) {
found = true;
break;
}
}
if (!found) {
reduced.push(aitem);
}
}
return reduced.concat(b);
}
const mergeByProperty = (target, source, prop) => {
source.forEach(sourceElement => {
let targetElement = target.find(targetElement => {
return sourceElement[prop] === targetElement[prop];
})
targetElement ? Object.assign(targetElement, sourceElement) : target.push(sourceElement);
})
}
var target /* arr1 */ = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var source /* arr2 */ = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
mergeByProperty(target, source, 'name');
console.log(target)
This answer was getting old, libs like lodash and underscore are much less needed these days. In this new version, the target (arr1) array is the one we’re working with and want to keep up to date. The source (arr2) array is where the new data is coming from, and we want it merged into our target array.
We loop over the source array looking for new data, and for every object that is not yet found in our target array we simply add that object using target.push(sourceElement) If, based on our key property ('name'), an object is already in our target array - we update its properties and values using Object.assign(targetElement, sourceElement). Our “target” will always be the same array and with updated content.
I always arrive here from google and I'm always not satisfy from the answers. YOU answer is good but it'll be easier and neater using underscore.js
DEMO: http://jsfiddle.net/guya/eAWKR/
Here is a more general function that will merge 2 arrays using a property of their objects. In this case the property is 'name'
var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
function mergeByProperty(arr1, arr2, prop) {
_.each(arr2, function(arr2obj) {
var arr1obj = _.find(arr1, function(arr1obj) {
return arr1obj[prop] === arr2obj[prop];
});
arr1obj ? _.extend(arr1obj, arr2obj) : arr1.push(arr2obj);
});
}
mergeByProperty(arr1, arr2, 'name');
console.log(arr1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>
[{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]
Very simple using ES6 spread operator:
const array1 = [{a: 'HI!'}, {b: 'HOW'}]
const array2 = [{c: 'ARE'}, {d: 'YOU?'}]
const mergedArray = [ ...array1, ...array2 ]
console.log('Merged Array: ', mergedArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Merged Array: [ {a: 'HI!'}, {b: 'HOW'} {c: 'ARE'}, {d: 'YOU?'} ]
Note: The above solution is to just merge two arrays using ES6 spread operator.
Edit on 07 January 2020 by @bh4r4th : As the context changed due to edits after my initial solution. I would like to update my solution to match current criteria. i.e.,
Merger array objects without creating duplicate objects and,
update the value
if the name
property already exists in the prior array
const arr1 = [
{ name: "lang", value: "English" },
{ name: "age", value: "18" }
]
const arr2 = [
{ name: "childs", value: '2' },
{ name: "lang", value: "German" }
]
const arr3 = [
{ name: "lang", value: "German" },
{ name: "age", value: "28" },
{ name: "childs", value: '5' }
]
// Convert to key value dictionary or object
const convertToKeyValueDict = arrayObj => {
const val = {}
arrayObj.forEach(ob => {
val[ob.name] = ob.value
})
return val
}
// update or merge array
const updateOrMerge = (a1, a2) => {
const ob1 = convertToKeyValueDict(a1)
const ob2 = convertToKeyValueDict(a2)
// Note: Spread operator with objects used here
const merged_obj = {...ob1, ...ob2}
const val = Object.entries(merged_obj)
return val.map(obj => ({ name: obj[0], value: obj[1] }))
}
const v1 = updateOrMerge(arr1, arr2)
const v2 = updateOrMerge(v1, arr3)
console.log(`Merged array1 and array2: ${JSON.stringify(v1)} \n\n`)
console.log(`Merged above response and array3: ${JSON.stringify(v2)} \n\n`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
var arr3 = [];
for(var i in arr1){
var shared = false;
for (var j in arr2)
if (arr2[j].name == arr1[i].name) {
shared = true;
break;
}
if(!shared) arr3.push(arr1[i])
}
arr3 = arr3.concat(arr2);
Merging two arrays:
var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var result=arr1.concat(arr2);
// result: [{name: "lang", value: "English"}, {name: "age", value: "18"}, {name : "childs", value: '5'}, {name: "lang", value: "German"}]
Merging two arrays without duplicated values for 'name':
var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var i,p,obj={},result=[];
for(i=0;i<arr1.length;i++)obj[arr1[i].name]=arr1[i].value;
for(i=0;i<arr2.length;i++)obj[arr2[i].name]=arr2[i].value;
for(p in obj)if(obj.hasOwnProperty(p))result.push({name:p,value:obj[p]});
// result: [{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With