157

I have two arrays:

Array 1:

[
 { id: "abdc4051", date: "2017-01-24" }, 
 { id: "abdc4052", date: "2017-01-22" }
]

and array 2:

[
 { id: "abdc4051", name: "ab" },
 { id: "abdc4052", name: "abc" }
]

I need to merge these two arrays based on id and get this:

[
 { id: "abdc4051", date: "2017-01-24", name: "ab" },
 { id: "abdc4052", date: "2017-01-22", name: "abc" }
]

How can I do this without iterating trough Object.keys?

Ivar
6,99912 gold badges58 silver badges69 bronze badges
asked Oct 20, 2017 at 12:39
5
  • 1
    are the arrays always sorted and have the same index for the same id? Commented Oct 20, 2017 at 13:07
  • 3
    This is what I would do: array1.map(x => { return array2.map(y => { if (y.id === x.id) { x.date = y.date; return x; } } } Commented Jan 8, 2019 at 0:14
  • @Thadeus Ajayi - This is proper way than what the ticked answer provided..Just filling the missed braces as below array1.map((x) => array2.map((y) => { if (y.id === x.id) { x.date = y.date; return x; } }) ); Commented Nov 25, 2020 at 9:49
  • @ThadeusAjayi can you explain why you have x.date = y.date? what function does that serve? I don't know Array.map very well. Commented Apr 29, 2022 at 14:57
  • 1
    @Jknight I guess it should be x.name = y.name since that's the field that needs to be updated. Commented May 3, 2022 at 22:15

25 Answers 25

137

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);


Use below code if arr1 and arr2 are in a different order:

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 merged = [];
for(let i=0; i<arr1.length; i++) {
 merged.push({
 ...arr1[i], 
 ...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}
 );
}
console.log(merged);

Use this if arr1 and arr2 are in a same order

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 merged = [];
for(let i=0; i<arr1.length; i++) {
 merged.push({
 ...arr1[i], 
 ...arr2[i]
 });
}
console.log(merged);

adiga
35.4k9 gold badges66 silver badges88 bronze badges
answered Oct 20, 2017 at 12:46
Sign up to request clarification or add additional context in comments.

9 Comments

This is merging the arrays only? It does not "join" on arr1.id == arr2.id as OP has asked.
Title is "Merge two array of objects based on a key". OP also mentions in post "based on id".
This does not respect a key / key-value. It just merge every item from array. The question was: How to merge two arrays by key. For arr1 you have to find the correct item from arr2 by key "id".
@Dominik Updated the answer as per OP's requirement.
Be careful one thing, the two arrays do have to have the exact same number of data and keys. If one has 2 key another has 3 key, it won't work.
|
81

This solution is applicable even when the merged arrays have different sizes. Also, even if the matching keys have different names.

Merge the two arrays by using a Map as follows:

const arr1 = [
 { id: "abdc4051", date: "2017-01-24" }, 
 { id: "abdc4052", date: "2017-01-22" },
 { id: "abdc4053", date: "2017-01-22" }
];
const arr2 = [
 { nameId: "abdc4051", name: "ab" },
 { nameId: "abdc4052", name: "abc" }
];
const map = new Map();
arr1.forEach(item => map.set(item.id, item));
arr2.forEach(item => map.set(item.nameId, {...map.get(item.nameId), ...item}));
const mergedArr = Array.from(map.values());
console.log(JSON.stringify(mergedArr));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Run the stack snippet to see the result:

[
 {
 "id": "abdc4051",
 "date": "2017年01月24日",
 "nameId": "abdc4051",
 "name": "ab"
 },
 {
 "id": "abdc4052",
 "date": "2017年01月22日",
 "nameId": "abdc4052",
 "name": "abc"
 },
 {
 "id": "abdc4053",
 "date": "2017年01月22日"
 }
]
Henke
5,9076 gold badges41 silver badges54 bronze badges
answered Feb 23, 2020 at 18:31

5 Comments

This is a better answer than the accepted answer as it allows for different keys and different sized arrays
This also solved my problem as I had to combine on a property and still return the objects that did not combine.
This is the modern answer as of Feb 2022. @Adel / Op should really consider changing the accepted answer.
Perfect, this answer has time complexity of O(n) while if we were to use map and find or some other combination, it would be O(n^2). Thanks a lot, I totally forgot about using Map for this problem
I'd like to add it acts like a right outer join, in case you have status in both objects, arr1 has status:1 and arr2 has status 0, arr2 status will show up in the end result
76

You can do this in one line

let arr1 = [
 { id: "abdc4051", date: "2017-01-24" },
 { id: "abdc4052", date: "2017-01-22" }
];
let arr2 = [
 { id: "abdc4051", name: "ab" },
 { id: "abdc4052", name: "abc" }
];
const mergeById = (a1, a2) =>
 a1.map(itm => ({
 ...a2.find((item) => (item.id === itm.id) && item),
 ...itm
 }));
console.log(mergeById(arr1, arr2));

  1. Map over array1
  2. Search through array2 for array1.id
  3. If you find it ...spread the result of array2 into array1

The final array will only contain id's that match from both arrays

Tushar Walzade
3,8274 gold badges39 silver badges60 bronze badges
answered Aug 3, 2018 at 12:15

4 Comments

great! what's the purpose of "&& item" in the find method?
@Fabrice my guess is that, when writing the answer, the (incorrect) assumption was that [].find() required the found item to be returned, rather than just a boolean. But since it's in the answer now, we can make up some use for it :-) Now it avoids a match if item is falsey. So it's a bit like a JOIN in a three-valued relational algebra such as SQL (won't equijoin on NULL). IOW, if the id is missing or falsey on either side, there's no match.
you don't need && item here, find will return found element. ...a2.find(item => item.id === itm.id),
&& item not needed. If there are no items, the predicate callback is never called, so why have it?
12

Here's an O(n) solution using reduce and Object.assign

const joinById = ( ...lists ) =>
 Object.values(
 lists.reduce(
 ( idx, list ) => {
 list.forEach( ( record ) => {
 if( idx[ record.id ] )
 idx[ record.id ] = Object.assign( idx[ record.id ], record)
 else
 idx[ record.id ] = record
 } )
 return idx
 },
 {}
 )
 )

To use this function for the OP's case, pass in the arrays you want to join to joinById (notice lists is a rest parameter).

let joined = joinById(list1, list2)

Each list gets reduced to a single object where the keys are ids and the values are the objects. If there's a value at the given key already, it gets object.assign called on it and the current record.

Here's the generic O(n*m) solution, where n is the number of records and m is the number of keys. This will only work for valid object keys. You can convert any value to base64 and use that if you need to.

const join = ( keys, ...lists ) =>
 lists.reduce(
 ( res, list ) => {
 list.forEach( ( record ) => {
 let hasNode = keys.reduce(
 ( idx, key ) => idx && idx[ record[ key ] ],
 res[ 0 ].tree
 )
 if( hasNode ) {
 const i = hasNode.i
 Object.assign( res[ i ].value, record )
 res[ i ].found++
 } else {
 let node = keys.reduce( ( idx, key ) => {
 if( idx[ record[ key ] ] )
 return idx[ record[ key ] ]
 else
 idx[ record[ key ] ] = {}
 return idx[ record[ key ] ]
 }, res[ 0 ].tree )
 node.i = res[ 0 ].i++
 res[ node.i ] = {
 found: 1,
 value: record
 }
 }
 } )
 return res
 },
 [ { i: 1, tree: {} } ]
 )
 .slice( 1 )
 .filter( node => node.found === lists.length )
 .map( n => n.value )

This is essentially the same as the joinById method, except that it keeps an index object to identify records to join. The records are stored in an array and the index stores the position of the record for the given key set and the number of lists it's been found in.

Each time the same key set is encountered, it finds the node in the tree, updates the element at it's index, and the number of times it's been found is incremented.

After joining, the idx object is removed from the array with the slice and any elements that weren't found in each set are removed. This makes it an inner join, you could remove this filter and have a full outer join.

Finally each element is mapped to it's value, and you have the joined arrays.

answered Oct 3, 2019 at 22:50

3 Comments

This is my preferred answer to go. Thanks so much for the detailed analysis on each solution proposed.
Sorry, this answer is incomprehensible to me. - For one thing: where am I supposed to insert the two example arrays supplied by the original poster of the question?
@Henke My apologies for not explaining that. The two arrays get passed into the first function. You can copy and paste it, pass the two arrays in and the joined result gets returned. I'll update the answer with an example using the OP's data.
11

You could use an arbitrary count of arrays and map on the same index new objects.

var array1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],
 array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }],
 result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

answered Oct 20, 2017 at 13:14

3 Comments

Will you please help me to understand this line result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i]))); What is happening here ? Is it comparing two arrays and assigning the values which got common keys ?
it takes all arrays for joining and maps the result of an assigned single element of a (the whole array), later c as item with b and the item b[i].
This code doesn't work when the ids are different or not in order var array1 = [{ id: "abdc4053", date: "2017年01月24日" }, { id: "abdc4054", date: "2017年01月22日" }], array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }], result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i]))); console.log(result);
10

If you have 2 arrays need to be merged based on values even its in different order

let arr1 = [
 { id:"1", value:"this", other: "that" },
 { id:"2", value:"this", other: "that" }
];
let arr2 = [
 { id:"2", key:"val2"},
 { id:"1", key:"val1"}
];

you can do like this

const result = arr1.map(item => {
 const obj = arr2.find(o => o.id === item.id);
 return { ...item, ...obj };
 });
console.log(result);
answered Oct 16, 2019 at 16:27

Comments

10

To merge the two arrays on id, assuming the arrays are equal length:

arr1.map(item => ({
 ...item,
 ...arr2.find(({ id }) => id === item.id),
}));
answered Jul 1, 2019 at 18:41

Comments

9

We can use lodash here. _.merge works as you expected. It works with the common key present.

_.merge(array1, array2)
answered Sep 2, 2020 at 13:25

Comments

5

Non of these solutions worked for my case:

  • missing objects can exist in either array
  • runtime complexity of O(n)

notes:

  • I used lodash but it's easy to replace with something else
  • Also used Typescript (just remove/ignore the types)
import { keyBy, values } from 'lodash';
interface IStringTMap<T> {
 [key: string]: T;
}
type IIdentified = {
 id?: string | number;
};
export function mergeArrayById<T extends IIdentified>(
 array1: T[],
 array2: T[]
): T[] {
 const mergedObjectMap: IStringTMap<T> = keyBy(array1, 'id');
 const finalArray: T[] = [];
 for (const object of array2) {
 if (object.id && mergedObjectMap[object.id]) {
 mergedObjectMap[object.id] = {
 ...mergedObjectMap[object.id],
 ...object,
 };
 } else {
 finalArray.push(object);
 }
 }
 values(mergedObjectMap).forEach(object => {
 finalArray.push(object);
 });
 return finalArray;
}
answered Jul 4, 2019 at 19:41

Comments

5

You can use array methods

let arrayA=[
{id: "abdc4051", date: "2017-01-24"},
{id: "abdc4052", date: "2017-01-22"}]
let arrayB=[
{id: "abdc4051", name: "ab"},
{id: "abdc4052", name: "abc"}]
let arrayC = [];
 
arrayA.forEach(function(element){
 arrayC.push({
 id:element.id,
 date:element.date,
 name:(arrayB.find(e=>e.id===element.id)).name
 }); 
});
console.log(arrayC);
//0:{id: "abdc4051", date: "2017-01-24", name: "ab"}
//1:{id: "abdc4052", date: "2017-01-22", name: "abc"}

answered Oct 20, 2017 at 12:49

1 Comment

The function isBiggerThan10() is just a left-over? Not really making any sense here?
4

Here is one-liner (order of elements in array is not important and assuming there is 1 to 1 relationship):

var newArray = array1.map(x=>Object.assign(x, array2.find(y=>y.id==x.id)))
answered Mar 24, 2021 at 9:58

1 Comment

I have found that - in SQL terms - this answer produces a left outer join, given that arr1 is the left array (table) and arr2 is the right array. (The original poster of the question has not clarified what type of join he would like as an answer.)
4

I iterated through the first array and used the .find method on the second array to find a match where the id are equal and returned the result.

const a = [{ id: "abdc4051", date: "2017-01-24" },{ id: "abdc4052", date: "2017-01-22" }];
const b = [{ id: "abdc4051", name: "ab" },{ id: "abdc4052", name: "abc" }];
console.log(a.map(itm => ({...itm, ...b.find(elm => elm.id == itm.id)})));

answered Apr 3, 2021 at 14:07

Comments

2

You can recursively merge them into one as follows:

function mergeRecursive(obj1, obj2) {
 for (var p in obj2) {
 try {
 // Property in destination object set; update its value.
 if (obj2[p].constructor == Object) {
 obj1[p] = this.mergeRecursive(obj1[p], obj2[p]);
 } else {
 obj1[p] = obj2[p];
 }
 } catch (e) {
 obj1[p] = obj2[p];
 }
 }
 return obj1;
}
arr1 = [
 { id: "abdc4051", date: "2017-01-24" },
 { id: "abdc4052", date: "2017-01-22" }
];
arr2 = [
 { id: "abdc4051", name: "ab" },
 { id: "abdc4052", name: "abc" }
];
mergeRecursive(arr1, arr2)
console.log(JSON.stringify(arr1))

Tushar Walzade
3,8274 gold badges39 silver badges60 bronze badges
answered Oct 20, 2017 at 12:52

Comments

2

Irrespective of the order you can merge it by,

function merge(array,key){
 let map = {};
 array.forEach(val=>{
 if(map[val[key]]){
 map[val[key]] = {...map[val[key]],...val};
 }else{
 map[val[key]] = val;
 }
 })
 return Object.keys(map).map(val=>map[val]);
}
let b = [
 { id: "abdc4051", name: "ab" },
 { id: "abdc4052", name: "abc" }
];
let a = [
 { id: "abdc4051", date: "2017-01-24" }, 
 { id: "abdc4052", date: "2017-01-22" }
];
console.log(merge( [...a,...b], 'id'));

answered Mar 18, 2021 at 10:21

1 Comment

Good answer. However, to me the important thing is whether the order of the objects in the two arrays destroys anything or not, which you don't really test for in your example above. So I tried your solution in a stack snippet of my own, and it turns out your solution works just fine in this respect as well. Thanks! Cheers.
1

An approach if both two arrays have non-intersect items.

const firstArray = [
 { id: 1, name: "Alex", salutation: "Mr." },
 { id: 2, name: "Maria", salutation: "Ms." },
];
const secondArray = [
 { id: 2, address: "Larch Retreat 31", postcode: "123452" },
 { id: 3, address: "Lycroft Close 12D", postcode: "123009" },
];
const mergeArr = (arr1, arr2) => {
 const obj = {};
 arr1.forEach(item => {
 obj[item.id] = item;
 });
 arr2.forEach(item => {
 obj[item.id]
 ? (obj[item.id] = { ...obj[item.id], ...item })
 : (obj[item.id] = item);
 });
 return Object.values(obj);
};
const output = mergeArr(firstArray, secondArray);
console.log(output);

answered Aug 13, 2021 at 9:59

Comments

1

Here is converting the best answer (jsbisht) into a function that accepts the keys as arguments.

const mergeArraysByKeyMatch = (array1, array2, key1, key2) => {
 const map = new Map();
 array1.forEach((item) => map.set(item[key1], item));
 array2.forEach((item) =>
 map.set(item[key2], { ...map.get(item[key2]), ...item })
 );
 const merged = Array.from(map.values());
 return merged;
};
answered Aug 3, 2022 at 18:21

Comments

0

Well... assuming both arrays are of the same length, I would probably do something like this:

var newArr = []
for (var i = 0; i < array1.length; i++ {
 if (array1[i].id === array2[i].id) {
 newArr.push({id: array1[i].id, date: array1[i].date, name: array2[i].name});
 }
}
answered Oct 20, 2017 at 12:47

1 Comment

My apologies, I missed the last line of your post. x_X
0

I was able to achieve this with a nested mapping of the two arrays and updating the initial array:

member.map(mem => {
return memberInfo.map(info => {
 if (info.id === mem.userId) {
 mem.date = info.date;
 return mem;
 }
 }
}
answered Jan 8, 2019 at 0:24

Comments

0

There are a lot of solutions available for this, But, We can simply use for loop and if conditions to get merged arrays.

const firstArray = [
 { id: 1, name: "Alex", salutation: "Mr." },
 { id: 2, name: "Maria", salutation: "Ms." },
];
const secondArray = [
 { id: 1, address: "Larch Retreat 31", postcode: "123452" },
 { id: 2, address: "Lycroft Close 12D", postcode: "123009" },
];
let mergedArray: any = [];
for (const arr1 of firstArray) {
 for (arr2 doc of secondArray) {
 if (arr1.id === arr2.id) {
 mergedArray.push({ ...arr1, ...arr2 });
 }
 }
}
console.log(mergedArray)
answered Oct 11, 2021 at 7:44

1 Comment

What I concern about this code is the complexity because it is O^(n*m) and is not efficient with huge data sizes
0

A Typescript O(n+m) (which could be classified as O(n)) solution; without lodash:

// RequireAtLeastOne from https://stackoverflow.com/questions/40510611/typescript-interface-require-one-of-two-properties-to-exist/49725198#49725198
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
 T,
 Exclude<keyof T, Keys>
> &
 {
 [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
 }[Keys];
export const mergeDualArraysOnKey = <
 K extends PropertyKey,
 T extends RequireAtLeastOne<{ [f in PropertyKey]?: unknown }, K>
>(
 key: K,
 ...lists: [T[], T[]]
): T[] => {
 const lookup: { [key in string]: number } = {};
 return lists[0].concat(lists[1]).reduce((acc: T[], value: T, i: number) => {
 const lookupKey = `${value[key]}`;
 if (lookup.hasOwnProperty(lookupKey)) {
 acc[lookup[lookupKey]] = Object.assign({}, acc[lookup[lookupKey]], value);
 } else {
 acc.push(value);
 lookup[lookupKey] = acc.length - 1;
 }
 return acc;
 }, []);
};

First concatenates the two arrays and then iterates through the newly created array. It uses a lookup table (object) to store the index of an item in the final merged array which has the same key and merges the objects inplace.

If this needed to be extended to handle more arrays, could use a loop or recursion as a wrapping function:

const mergeArrays = <
 K extends PropertyKey,
 T extends RequireAtLeastOne<{ [f in PropertyKey]?: unknown }, K>
>(
 key: K,
 ...lists: T[][]
): T[] => {
 if (lists.length === 1) {
 return lists[0];
 }
 const l1 = lists.pop() || [];
 const l2 = lists.pop() || [];
 return mergeArrays(key, mergeDualArraysOnKey(key, l1, l2), ...lists);
};

with usage being:

const arr1 = [
 { id: "abdc4052", date: "2017年01月22日" },
 { id: "abdc4052", location: "US" },
 { id: "abdc4051", date: "2017年01月24日" },
 { id: "abdc4053", date: "2017年01月24日" },
 { id: "abdc4054", date: "2017年01月24日" },
 { id: "abdc4055", location: "US" },
];
const arr2 = [
 { id: "abdc4052", date: "2017年01月22日" },
 { id: "abdc4052", name: "abc" },
 { id: "abdc4055", date: "2017年01月24日" },
 { id: "abdc4055", date: "2017年01月24日", name: "abcd" },
];
const arr3 = [{ id: "abdc4056", location: "US" }];
const arr4 = [
 { id: "abdc4056", name: "abcde" },
 { id: "abdc4051", name: "ab--ab" },
];
mergeArrays<
 "id",
 {
 id: string;
 date?: string;
 location?: string;
 name?: string;
 }
 >("id", arr1, arr2, arr3, arr4)
answered Aug 27, 2022 at 14:05

Comments

0

Base on your example, you can do it this way:

const arrayOne = [
 { id: "abdc4051", date: "2017年01月24日" }, 
 { id: "abdc4052", date: "2017年01月22日" }
]
const arrayTwo = [
 { id: "abdc4051", name: "ab" },
 { id: "abdc4052", name: "abc" }
]
const mergeArrays = () => {
 arrayOne.forEach((item, i) => {
 const matchedFound = arrayTwo.findIndex(a => a.id === item.id);
 arrayOne[i] = {
 ...item,
 ...matchedFound,
 }
 });
};
mergeArrays();
console.log(arrayOne);
answered Dec 14, 2022 at 7:39

Comments

0

✅ TypeScript version here!

Below is a more scalable solution to the problem, because it allows you to determine the key based on which the arrays will be merged. The callbackFn is used to determine this key.

/**
 * Merges two arrays of objects (`arrayA` and `arrayB`) into one, resolving conflicts based on a key returned by the `callbackFn`.
 * For objects with the same key, properties from the objects in the second array (`arrayB`) overwrite those in the first (`arrayA`).
 *
 * @template TItem Extends object, the type of elements in the arrays to be merged.
 * @template TKey The type of the key used to identify unique objects.
 * @param {TItem[]} arrayA The first array of objects to merge.
 * @param {TItem[]} arrayB The second array of objects to merge.
 * @param {(value: TItem) => TKey} callbackFn A callback function that generates a key for each object based on its value. Used to identify and resolve conflicts between objects.
 * @returns {TItem[]} A new array containing merged objects from `arrayA` and `arrayB`. In case of conflicts, properties from `arrayB` objects take precedence.
 * @example
 *
 * const mergedArray = merge(
 * [{ id: 1, name: "John" }, { id: 2, name: "Alice" }],
 * [{ id: 1, age: 18 }, { id: 3, name: "Bob" }],
 * (element) => element.id
 * );
 * // [{ id: 1, name: "John", age: 18 }, { id: 2, name: "Alice" }, { id: 3, name: "Bob" }]
 */
export function merge<TItem extends object, TKey>(
 arrayA: TItem[],
 arrayB: TItem[],
 callbackFn: (value: TItem) => TKey
): TItem[] {
 const map = new Map<TKey, TItem>();
 arrayA.forEach((item) => {
 const key = callbackFn(item);
 map.set(key, item);
 });
 
 arrayB.forEach((item) => {
 const key = callbackFn(item);
 const oldItem = resultMap.get(key);
 map.set(key, { ...oldItem, ...item });
 });
 
 return Array.from(map.values());
}

Usage:

Below is the use of this function for OP data:

const arr1 = [
 { id: "abdc4051", date: "2017年01月24日" },
 { id: "abdc4052", date: "2017年01月22日" }
];
const arr2 = [
 { id: "abdc4051", name: "ab" },
 { id: "abdc4052", name: "abc" }
];
const mergedArray = merge(arr1, arr2, (item) => item.id)
console.log(mergedArray);
answered Mar 26, 2024 at 16:07

Comments

-1

Python 3 Solution for someone who lands on this page in hope of finding one

def merge(studentDetails, studentMark, merge_key):
 student_details = {}
 student_marks = {}
 for sd, sm in zip(studentDetails, studentMark):
 key = sd.pop(merge_key)
 student_details[key] = sd
 key = sm.pop(merge_key)
 student_marks[key] = sm
 res = []
 for id, val in student_details.items():
 # Merge three dictionary together
 temp = {**{"studentId": id}, **val, **student_marks[id]}
 res.append(temp)
 return res
if __name__ == '__main__':
 # Test Case 1
 studentDetails = [
 {"studentId": 1, "studentName": 'Sathish', "gender": 'Male', "age": 15},
 {"studentId": 2, "studentName": 'kumar', "gender": 'Male', "age": 16},
 {"studentId": 3, "studentName": 'Roja', "gender": 'Female', "age": 15},
 {"studentId": 4, "studentName": 'Nayanthara', "gender": 'Female', "age": 16},
 ]
 studentMark = [
 {"studentId": 1, "mark1": 80, "mark2": 90, "mark3": 100},
 {"studentId": 2, "mark1": 80, "mark2": 90, "mark3": 100},
 {"studentId": 3, "mark1": 80, "mark2": 90, "mark3": 100},
 {"studentId": 4, "mark1": 80, "mark2": 90, "mark3": 100},
 ]
 # Test Case 2
 array1 = [
 {"id": "abdc4051", "date": "2017年01月24日"},
 {"id": "abdc4052", "date": "2017年01月22日"}
 ]
 array2 = [
 {"id": "abdc4051", "name": "ab"},
 {"id": "abdc4052", "name": "abc"}
 ]
 output = merge(studentDetails, studentMark, merge_key="studentId")
 [print(a) for a in output]
 output = merge(array1, array2, merge_key="id")
 [print(a) for a in output]

Output

{'studentId': 1, 'studentName': 'Sathish', 'gender': 'Male', 'age': 15, 'mark1': 80, 'mark2': 90, 'mark3': 100}
{'studentId': 2, 'studentName': 'kumar', 'gender': 'Male', 'age': 16, 'mark1': 80, 'mark2': 90, 'mark3': 100}
{'studentId': 3, 'studentName': 'Roja', 'gender': 'Female', 'age': 15, 'mark1': 80, 'mark2': 90, 'mark3': 100}
{'studentId': 4, 'studentName': 'Nayanthara', 'gender': 'Female', 'age': 16, 'mark1': 80, 'mark2': 90, 'mark3': 100}
{'studentId': 'abdc4051', 'date': '2017-01-24', 'name': 'ab'}
{'studentId': 'abdc4052', 'date': '2017-01-22', 'name': 'abc'}
answered Jul 6, 2022 at 4:24

Comments

-1

I think you can just use simple JS here. Here is the simple step where you can generate the same output.

const keyValuePair = function(arr1, arr2) {
 return arr1.map((item, index) => {
 return {...item, ...arr2[index]}
 });
}
console.log(keyValuePair([
 { id: "abdc4051", date: "2017-01-24" }, 
 { id: "abdc4052", date: "2017-01-22" }
 ], [
 { id: "abdc4051", name: "ab" },
 { id: "abdc4052", name: "abc" }
 ]))

answered Nov 24, 2023 at 11:59

1 Comment

Your solution will only work if both arrays have exactly the same objects in the same order, with relation to the id property ofc. In the real world, it isn't as simple as that.
-2

This is a version when you have an object and an array and you want to merge them and give the array a key value so it fits into the object nicely.

var fileData = [
 { "id" : "1", "filename" : "myfile1", "score" : 33.1 }, 
 { "id" : "2", "filename" : "myfile2", "score" : 31.4 }, 
 { "id" : "3", "filename" : "myfile3", "score" : 36.3 }, 
 { "id" : "4", "filename" : "myfile4", "score" : 23.9 }
];
var fileQuality = [0.23456543,0.13413131,0.1941344,0.7854522];
var newOjbect = fileData.map((item, i) => Object.assign({}, item, {fileQuality:fileQuality[i]}));
console.log(newOjbect);

answered Mar 11, 2020 at 17:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.