Inner join two array with objects jquery or javascript

Viewed 706

I have 2 arrays consists of a few objects

const colors=[
{id: 5, color: "yellow"}
{id: 6, color: "green"}
];

const boxes=[
{color_id: 5, name: 4, value: 40}
{color_id: 5, name: 5, value: 50}
{color_id: 6, name: 4, value: 400}
{color_id: 6, name: 5, value: 500}
]

and i want this result

var result=[
{color_id: 5, name: 4, value: 40, color: "yellow"}
{color_id: 5, name: 5, value: 50, color: "yellow"}
{color_id: 6, name: 4, value: 400, color: "green"}
{color_id: 6, name: 5, value: 500, color: "green"}
]

My solution after searches is

   const result = [];
   $.each(boxes,function(index,value){
   result.push($.extend({}, colors[index], boxes[index]));
   });

but it's not work

3 Answers

With Javascript:

    var result = boxes.map(b => {
    colors.forEach(c => {
        if (c.id === b.color_id)
            for (key in c) {
                key !== 'id' ? (b[key] = c[key]) : null
            }
    })
    return b
 })

This way it will add any additional key:value from colors as well. (i.e. if any or in future)

You can use .filter() with .each()

var colors=[
{id: 5, color: "yellow"},
{id: 6, color: "green"}
];

var boxes=[
{color_id: 5, name: 4, value: 40},
{color_id: 5, name: 5, value: 50},
{color_id: 6, name: 4, value: 400},
{color_id: 6, name: 5, value: 500}
];

var result = boxes;  // result to equal the boxes array
$.each(result , function(i , val){
  var colors_match = colors.filter(function(v){
    return v.id == val.color_id;
  });
  result[i]['color'] = colors_match[0].color;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

const arr = boxes.map(box => {
    const color = colors.find(color => color.id === box.color_id).color
    return { ...box, color };
});
Related