-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!

7
  • 1
    what does not work? please add your code. Commented Apr 3, 2021 at 13:49
  • @Nina Scholz It's not that the code is not working. OP wants a simple solution to the given problem Commented Apr 3, 2021 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? Commented Apr 3, 2021 at 13:55
  • My bad @Nina Scholz, will keep that in mind. Commented Apr 3, 2021 at 13:57
  • 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. Commented Apr 3, 2021 at 14:12

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

I can't see the trick conditionally add properties to an Object. @EdisonPebojot
@EdisonPebojot Pls double-check my answer with the other one then give me your feedback. Thanks
What am I missing? I'd appreciated your feedback @EdisonPebojot

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.