Adding Property to another Array of objects from another set of Array of Objects

Lets say I have 2 Array of objects and I want to conditionally add one to the other.

let aData = [
  {
    id: 1,
    item: "shirt",
    price: "24.99",
    quantity: "1"
  },
  {
    id: 2,
    item: "pants",
    price: "34.99",
    quantity: "5"
  }
]

let bData = [
  {
    id: 1,
    item_id: 1,
    url: "imagelink.jpg"
  },
  {
    id: 2,
    item_id: 1,
    url: "image2link.jpg"
  },
  {
    id: 3,
    item_id: 2,
    url: "image3link.jpg"
  },
  {
    id: 4,
    item_id: 2,
    url: "image4link.jpg"
  {
]

What I would like is to add all of bData to aData if the bData[i].item_id == aData[i].id

let cData = [
  {
    id: 1,
    item: "shirt",
    price: "24.99",
    quantity: "1",
    images: [
      {
        id: 1,
        item_id: 1,
        url: "imagelink.jpg"
      },
      {
        id: 2,
        item_id: 1,
        url: "image2link.jpg"
      }
    ]
  },
  {
   etc...
  }
]

I am at a standstill and this is what I’ve came up with so far

let temp = [];
for (i = 0; i < aData.length; i++) {
        let temp2 = [];
        
        temp2.push(aData[i]);
        let tempImages = {};
        for (k = 0; k < bData.length; k++) {
          if (aData[i].id == bData[k].item_id) {
            
            tempImages[k] = bData[k];
          }
        }
        temp2.images = tempImages;
        temp.push(temp2)
      }

This is not doing what I need

Answer

I would rather to use map and filter to do the job in a very clean way.

the code should be:

const result = aData.map(a => {
  a.images = bData.filter(b => b.item_id === a.id);
  return a;
})

here is a working example with your sample data.

let aData = [{
    id: 1,
    item: "shirt",
    price: "24.99",
    quantity: "1"
  },
  {
    id: 2,
    item: "pants",
    price: "34.99",
    quantity: "5"
  }
]

let bData = [{
    id: 1,
    item_id: 1,
    url: "imagelink.jpg"
  },
  {
    id: 2,
    item_id: 1,
    url: "image2link.jpg"
  },
  {
    id: 3,
    item_id: 2,
    url: "image3link.jpg"
  },
  {
    id: 4,
    item_id: 2,
    url: "image4link.jpg"
  }
]

const result = aData.map(a => {
  // use Object.assign to avoid changing the reference of aData
  const completeObject = Object.assign({}, a)
  completeObject.images = bData.filter(b => b.item_id === a.id);
  return completeObject;
})

console.log(result)

Leave a Reply

Your email address will not be published. Required fields are marked *