Lets say I have an object with image urls.
const imageURL = {
brakePad: "some_url_string",
tieRodEnd: "some_url_string",
rackEnd: "some_url_string",
};
I also have an array of products.
const products = [
{
type : 'brakePad',
brand : 'Akebono',
img : // i would like to pass the type value to the
// imageURL object to get the url ; in this instance
// brakePad
// i know i can pass it as img: imageURL['brakePad']
// but that is not what i am trying to achieve.
// is there any way i could extract the value of
// the type property and pass it to the imageURL
//object as the key
} ,
{
// similar object
},
];
i would like to pass the type value to the imageURL object to get the url. i know i can pass it as img: imageURL['brakePad'] but that is not what i am trying to achieve. is there any way i could extract the value of the type property and pass it to the imageURL object as the key Thanks
You can use map to get an array of URL's from iterating over the products array.
const result = imageURL[products[0].type];
const products = [
{
type: "brakePad",
brand: "Akebono",
img: "url",
},
{
type: "tieRodEnd",
brand: "Akebono",
img: "url",
},
];
const imageURL = {
brakePad: "some_url_string",
tieRodEnd: "some_url_string",
rackEnd: "some_url_string",
};
const result = products.map((o) => imageURL[o.type]);
console.log(result);
You can iterate over the products array and then use the type value for each product,
e.g using for...of loop,
for (let product of products) {
// here you have access to individual product
imageURL[product.type] // brakepad, tierodend ...
}
or conventional for loop:
for (let i = 0; i < products.length; i++) {
const type = products[i].type
imageURL[type]
}
If you want to add the image URL to the product objects you can map over the products array e.g,
const imageURL = {
brakePad: "some_url_string",
tieRodEnd: "some_url_string",
rackEnd: "some_url_string",
}
const products = [
{
type: 'brakePad',
brand: 'Akebono',
},
{
type: 'tieRodEnd',
brand: 'MONSTER',
}
]
const newProducts = products.map((product)=> {
return {...product, img: imageURL[product.type]}
})
console.log(newProducts)
You can read more about map method here at mdn
Or if you would like to add to the existing objects instead of creating a new array using map, then:
for (let product of products) {
product.img = imageURL[product.type]
}
console.log(products)