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 two array of objects based on a key value compare
You can do something like this:
const users = [
{
p_id: 1,
name: "Peter",
status: "Active",
},
{
p_id: 2,
name: "Kane",
status: "Active",
},
{
p_id: 3,
name: "William",
status: "Inactive",
},
];
const phoneNumbers = [
{ p_id: 1, type: "home", no: "+01 234 5678" },
{ p_id: 1, type: "work", no: "+09 111 2223" },
{ p_id: 2, type: "home", no: "+12 345 6789" },
];
const mergeArrays = (arr1, arr2) => {
return arr1.map((obj) => {
const numbers = arr2.filter((nums) => nums["p_id"] === obj["p_id"]);
if (!numbers.length) {
obj.phone = numbers;
return obj;
}
obj.phone = numbers.map((num) => ({ type: num.type, no: num.no }));
return obj;
});
};
const result = mergeArrays(users, phoneNumbers);
console.log(result);
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 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);
Merge two arrays of objects based on nested object key and value
The following code combines the two arrays like you specified:
// Data
const variants = [{"name":"Name 1","variationValues":{"P00003":"mappedValue1"}},{"name":"Name 2","variationValues":{"P00003":"mappedValue2"}},{"name":"Name 3","variationValues":{"P00003":"mappedValue3"}}];
const variationAttributes = [{"id":"P00003","name":"Variant Name","attributes":[{"name":"Variant Name 1","description":"Variant Description 1","attribute":"mappedValue1"},{"name":"Variant Name 2","description":"Variant Description 2","attribute":"mappedValue2"},{"name":"Variant Name 3","description":"Variant Description 3","attribute":"mappedValue3"}]}];
// Solution code
console.log( getMappedVariants() );
function getMappedVariants() {
return variants.map((variant) => ({
...variant,
variationValues: mapValuesToAttributes(variant.variationValues),
}));
}
function mapValuesToAttributes(values) {
const attributes = {};
for (const id in values) attributes[id] = findAttribute(id, values[id]);
return attributes;
}
function findAttribute(id, value) {
const variation = variationAttributes.find((v) => v.id === id);
const attribute = variation.attributes.find((a) => a.attribute === value);
return attribute;
}
Merge multiple array of objects based on a key
You could flatten your array and reduce values.
response.flat().reduce((acc, value) => {
let existingValueIndex = acc.findIndex(obj => obj.topic === value.topic);
if (existingValueIndex === -1) {
acc.push({ ...value });
return acc;
}
acc[existingValueIndex] = {
...acc[existingValueIndex],
...value,
};
return acc;
}, []);
It's not really efficient if you have big arrays.
You can also use a Set
to keep track on Topic names and prevent searching in the array for each iteration.
Merge two n number of array of objects based on a key
This looks like a case for Array.reduce
.
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
The signature is:
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
The approach here is to add items using their date
property as a key to a "map" object that starts out initialized as an empty object, then summing in the clicks properties you care about. At the end, result
will be an object and we can use Object.values()
to turn it's values into an array. We choose to use an object internally here to for faster lookup of existing dates, you could reduce using an array instead, but naively using arr.find
would net you a O(n2) solution.
const arr1 = [
{ old_clicks: 1, date: "2017-01-24" },
{ old_clicks: 4, date: "2017-01-22" },
{ old_clicks: 6, date: "2017-01-21" }
];
const arr2 = [
{ total_clicks: 120, date: "2017-01-21" },
{ total_clicks: 100, date: "2017-01-19" }
];
const mergeById = (...arrs) => {
const result = arrs.flat().reduce((acc, obj) => {
acc[obj.date] = {
date: obj.date,
total_clicks: (acc[obj.date]?.total_clicks ?? 0) + (obj?.total_clicks ?? 0),
old_clicks: (acc[obj.date]?.old_clicks ?? 0) + (obj?.old_clicks ?? 0),
}
return acc;
}, {})
return Object.values(result);
}
console.log(mergeById(arr1, arr2))
Merge objects with the same key in 2 arrays into one array in Javascript/React
You could take a dynamic approach by using an object with wanted keys fro the final result.
const
itemsFr = [{ title: "Bonjour" }, { title: "Bonne Nuit" }],
itemsEn = [{ title: "Good Morning" }, { title: "Good Night" }],
result = Object
.entries({ fr: itemsFr, en: itemsEn })
.reduce((r, [key, a]) => a.map(({ title }, i) => ({
title: { ...r[i]?.title, [key]: title }
})), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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>
Related Topics
How to Detect Internet Speed in JavaScript
JavaScript Call() & Apply() VS Bind()
What's the Right Way to Decode a String That Has Special HTML Entities in It
CSS Transitions Do Not Work When Assigned Trough JavaScript
How to Set Prefixed CSS3 Transitions Using JavaScript
Vertical Centering Variable Height Image While Maintaining Max-Width/Height
Divide Semi Circle with Stroke-Dasharray and on Active Color Fill
Ruby's ||= (Or Equals) in JavaScript
Detect Click Outside React Component
Sort Array Elements (String with Numbers), Natural Sort
What Is the JavaScript ≫≫≫ Operator and How to Use It
Prevent Address-Bar Hiding in Mobile Browsers
Can Jquery Change CSS Style Definition? (Not Individual CSS of Each Element)
Google Maps Not Rendering Completely on Page