Search code examples
javascriptarraysarray-maparray-filter

Replacing values of an array based on values from another array


I have the following array type

export const images = [
  { id: "000012", label: "night sky", cost: "35" },
  { id: "000013", label: "country road", cost: "16" },
  { id: "000014", label: "baseball game", cost: "12" },
  { id: "000015", label: "horse racing", cost: "24" },
  { id: "000016", label: "bike gathering", cost: "18" },
  ...
  { id: "001138", label: "kite surfing", cost: "25" },

and also have the following 2nd array

const product = [
  { product: "000013" },
  { product: "000016" },
  ...
]

and I'd like to replace the values of my product array with the label's value of my first array. The second array holds the id value of the first array in the product property. Expected outcome would be:

const product = [
  { product: "country road" },
  { product: "bike gathering" },
]

Solution

  • Here i ran a loop through each product and then find the corresponding image for it. And finally updated the product value with the image label.

    const images = [
      { id: "000012", label: "night sky", cost: "35" },
      { id: "000013", label: "country road", cost: "16" },
      { id: "000014", label: "baseball game", cost: "12" },
      { id: "000015", label: "horse racing", cost: "24" },
      { id: "000016", label: "bike gathering", cost: "18" },
      { id: "001138", label: "kite surfing", cost: "25" },
    ]
    
    const products = [
      { product: "000012" },
      { product: "000013" },
      { product: "000014" },
      
    ]
    
    products.forEach((p, index) => {
        const image = images.find(({id}) => id === p.product);
        if(image) {
          const newVal = {product: image.label};
          products[index] = {...p, ...newVal};
        }
    })
    
    console.log(products)