Merge 2 Arrays of Objects

Merge two array of objects based on a key

You can do it like this -

let arr1 = [

{ id: "abdc4051", date: "2017-01-24" },

{ id: "abdc4052", date: "2017-01-22" }

];

let arr2 = [

{ id: "abdc4051", name: "ab" },

{ id: "abdc4052", name: "abc" }

];

let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));

console.log(arr3);

Merge 2 arrays of objects but concat arrays if properties has the same value

You are correct in that Lodash's mergeWith doesn't merge recursively. You can manage this yourself manually.

  1. First iterate the first array and generate a map object by the name property.
  2. Then iterate the second array and check if the name property
    matches, and if so, recursively call the merge function to merge
    the two nested arrays from source and target arrays, otherwise, add
    the second array's element to the object map.
  3. Finally, convert the
    map object back to an array of the merged values.

Code:

const merge = (sourceArr, targetArr) => {
// (1) generate lookup map
const objMap = sourceArr.reduce((map, curr) => {
return {
...map,
[curr.name]: curr
};
}, {});

// (2) Merge objects, recurse on items arrays
targetArr.forEach((obj) => {
if (objMap[obj.name]) {
objMap[obj.name].items = merge(objMap[obj.name].items, obj.items);
} else {
objMap[obj.name] = obj;
}
});

// (3) Return merged values array
return Object.values(objMap);
};

const sourceObj = [
{
items: [
{ items: [{ id: "0", name: "z" }], name: "m" },
{ items: [{ id: "2", name: "q" }], name: "l" }
],
name: "c"
},
{
items: [{ items: [{ id: "4", name: "-" }], name: "v" }],
name: "d"
}
];

const targetObj = [
{
items: [
{ items: [{ id: "1", name: "d" }], name: "m" },
{ items: [{ id: "3", name: "b" }], name: "j" }
],
name: "c"
}
];

const merge = (sourceArr, targetArr) => {
const objMap = sourceArr.reduce((map, curr) => {
return {
...map,
[curr.name]: curr
};
}, {});

targetArr.forEach((obj) => {
if (objMap[obj.name]) {
objMap[obj.name].items = merge(objMap[obj.name].items, obj.items);
} else {
objMap[obj.name] = obj;
}
});

return Object.values(objMap);
};

const res = merge(sourceObj, targetObj);

console.log(res);

Merge two array of objects based on matching properties

There is a mistake in your arr2. The surname for 2nd item should be kohli instead of kolhi. Anyway, You can do the following to merge two array based on dynamic matching attribute. What we are doing here is,

For each item of arr1 we are finding the keys using Object.keys method and checking which object from arr2 has maximum matching object with the item of arr1. Then we merge the two item together.

arr1 = [
{
name: 'Rohan',
surname: 'Mehra',
age: '15',
date: "2021-01-19",
location: 'Goa'
},
{
name: 'Aman',
surname: 'Kohli',
age: '14',
date: "2021-01-19",
location: 'Kolkata'
},
{
name: 'Sam',
surname: 'Sharma',
age: '16',
date: "2021-01-21",
location: 'Mumbai'
}
]

arr2 = [
{
rollNo: 1,
marks: 100,
name: 'Rohan',
date: "2021-01-19",
},
{
rollNo: 2,
marks: 90,
surname: 'Kohli',
date: "2021-01-19",
},
{
rollNo: 3,
marks: 70,
date: "2021-01-21",
ExamCenter: {
place: 'Mumbai'
}
}
]

res = arr1.map(item => {
keys1 = Object.keys(item);
let max = 0;
const temp = arr2.reduce((prev, item2) => {
maxTemp = keys1.filter(key => item[key] === item2[key]).length;

if(maxTemp > max) {
max = maxTemp;
prev = item2;
}
return prev;
}, {})

if(temp) {
return {...item, ...temp}
}
});

console.log(res);

How can I merge two arrays of objects in JavaScript

const result = A.concat(B.filter(bo => A.every(ao => ao.id != bo.id)));

Concatenate all the objects from A with objects from B that aren't in A (which is done by filtering only objects from B where there isn't an object in A with the same id).

Example:

const A = [{id: "price", value: "1"}];

const B = [{id: "price", value: "0"}, {id: "number", value: "0"}];

const result = A.concat(B.filter(bo => A.every(ao => ao.id != bo.id)));

console.log(result);

Lodash - How to merge two arrays of objects based on key?

You can get the result using merge and keyBy lodash functions.

var array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}];
var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

var merged = _.merge(_.keyBy(array1, 'id'), _.keyBy(array2, 'id'));
var values = _.values(merged);
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

How to Merge two array of objects based on same key and value in javascript?

You can use map instead

let videos = [
{ id: 1, product_id: "training_video_test_1", video_title: "Video title 1", video_short_description: "desc 1" },
{ id: 2, product_id: "training_video_test_2", video_title: "Video title 2", video_short_description: "desc 2" },
{ id: 3, product_id: "training_video_test_3", video_title: "Video title 3", video_short_description: "desc 3" },
];

let storeProducts = [
{ product_id: "training_video_test_1", prduct_title: "training_video_test_1", price: 100 },
{ product_id: "training_video_test_2", prduct_title: "training_video_test_2", price: 100 },
];

const result = videos.map(v => ({ ...v, ...storeProducts.find(sp => sp.product_id === v.product_id) }));

console.log(result);

Merge 2 arrays of object based on specific object key

You can use Array.reduce() to combine the two arrays into one.

We start by concatenating and then grouping by id. For each item with the same ids we combine the selected arrays.

const arr1 = [ { id: "A527CFFE", selected: [ { itemId: "A1", text: "Selected 1" } ] } ]
const arr2 = [ { id: "A527CFFE", selected: [ { itemId: "A2", text: "Selected 2" } ] } ]

const result = Object.values([...arr1, ...arr2].reduce((acc, { id, selected }) => {
acc[id] = acc[id] || { id, selected: [] };
acc[id].selected = [...acc[id].selected, ...selected];
return acc;
}, {}));

console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }


Related Topics



Leave a reply



Submit