skip to Main Content

I have 2 arrays of objects:

array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];

I want to merge them so it looks like this:

[{"id":1,"cost":200,"qty":56,"desc":"a good one"},{"id":2,"cost":100,"qty":16,"desc":"a bad one"}];

Please notice the new array has properties from both arrays but it left out the object that was not present in the first one.

I tried this:

var mergethem = function() {
     var array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}];
     var array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}];
    
     var newarray= array2.filter(i => array1.map(a=> { if(a.id == i.id) i.qty = a.qty; return i; }));
     
     return newarray.filter(i=> { if(i.qty) return i; });
    }
    
    console.log(mergethem());

this seems to work sometimes and some times it doesn’t depending on the environment. I can’t pinpoint what the problem is so I would like to ask for alternatives to try out.

2

Answers


  1. You could get references of the objects of the second array and map the first while adding properties of the second array, if exist.

    const
        array1 = [{ id: 1, cost: 200, qty: 56 }, { id: 2, cost: 100, qty: 16 }],
        array2 = [{ id: 1, cost: 200, desc: "a good one" }, { id: 2, cost: 100, desc: "a bad one" }, { id: 3, cost: 50, desc: "an okay one" }],
        references2 = Object.fromEntries(array2.map(o => [o.id, o])),
        result = array1.map(o => ({ ...o, ...references2[o.id] }));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
  2. const array1 = [
      {"id":1,"cost":200,"qty":56},
      {"id":2,"cost":100,"qty":16}
    ];
    
    const array2 = [
      {"id":1,"cost":200,"desc":"a good one"},
      {"id":2,"cost":100,"desc":"a bad one"},
      {"id":3,"cost":50,"desc":"an okay one"}
    ];
    
    const result = array1.reduce((previousValue, currentValue) => {
      const needObj = array2.find(o => o.id === currentValue.id) ?? {};
      previousValue.push({...currentValue, ...needObj});
      return previousValue;
    }, []);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search