-3

I have two arrays of objects and want to combine the two based on specific key-value pairs. For example, I want to merge each of the objects in the arrays if they have the same values for 'fruit' key:

const a = [
    {fruit: 'banana', price: 100, quality:'high'},
    {fruit: 'orange', price:50, quality:'average'}
];

const b = [
    {fruit: 'banana', count: 4},
    {fruit: 'orange', count: 10}
];

const result = [
    {fruit: 'banana', price:100, quality:'high', count:4},
    {fruit: 'orange', price:50, quality:'average', count:10 }
];

The arrays a and b are defined such that they have the same length.

Thought about creating new empty arrays (e.g. 'banana' and 'orange') and then pushing relevant elements from each of the defined arrays, but this is probably overkilled and would love it if someone can help me out by showing a simple way to do this.

Thanks!

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
J.Ko
  • 6,561
  • 3
  • 12
  • 28
  • 1
    what does not work? please add your code. – Nina Scholz Apr 03 '21 at 13:49
  • @Nina Scholz It's not that the code is not working. OP wants a simple solution to the given problem – Fardeen Panjwani Apr 03 '21 at 13:52
  • @FardeenPanjwani SO is not a free code-writing service. OP has to show some effort to solve this on his/her own -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Apr 03 '21 at 13:55
  • My bad @Nina Scholz, will keep that in mind. – Fardeen Panjwani Apr 03 '21 at 13:57
  • [Searching the full title of the question with no changes](https://www.google.com/search?q=Merge+elements+of+two+different+array+of+objects+based+on+a+specific+key-value+pair+site%3Astackoverflow.com) – adiga Apr 03 '21 at 13:59
  • Okay. My bad that I didn't search enough and am not familiar with the SO etiquette, but wow, don't have to be so harsh, right? Thanks for those who posted their suggestions here. For those who took care to downvote and comment the search results, take it easy. World is already full of hate and stress. – J.Ko Apr 03 '21 at 14:09
  • 1
    I literally googled the title of the question and added couple of duplicates. Please check those out. They are useful. Downvotes are for the post. They are not personal nor harsh. The purpose of SO is to create a high quality Q & A. Seeing the same questions everyday without bare minimum research becomes tiresome. – adiga Apr 03 '21 at 14:12

2 Answers2

1

You can use something like this:

const a = [
        {fruit: 'banana', price: 100, quality:'high'},
        {fruit: 'orange', price:50, quality:'average'}
    ];

    const b = [
        {fruit: 'banana', count: 4},
        {fruit: 'orange', count: 10}
    ];

    /*** SOLUTION ***/
    let merged = [];
    for(let i=0; i < a.length; i++) {
      merged.push({
       ...a[i], 
       ...(b.find((itmInner) => itmInner.fruit === a[i].fruit))}
      );
    }
    console.log(merged)
1

Solution 1: In case of the order of data and/or the different length

You can do the trick to render count property by using Conditionally add properties to an Object like this

const a = [{fruit: 'banana', price: 100, quality:'high'},{fruit: 'orange', price:50, quality:'average'}];
const b = [{fruit: 'banana', count: 4},{fruit: 'orange', count: 10}];

const result = a.map(({fruit, price, quality}) => {
  const index = b.findIndex(r => r.fruit === fruit);
  return  {
            fruit, price, quality, 
            ...(index >= 0 && {count: b[index].count}) // the trick here
          };
});
console.log(result);

Solution 2: If the 2 arrays make sure that the same length and order, you can do simply like this

const a = [{fruit: 'banana', price: 100, quality:'high'},{fruit: 'orange', price:50, quality:'average'}];
const b = [{fruit: 'banana', count: 4},{fruit: 'orange', count: 10}];

const result = a.map((item, index) => Object.assign({}, item, b[index]));
//equivalent to: a.map((item, index) => ({...item, ...b[index]}));
console.log(result);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56