Digamos que tengo un objeto con URL de imagen.
const imageURL = { brakePad: "some_url_string", tieRodEnd: "some_url_string", rackEnd: "some_url_string", };También tengo una variedad de productos.
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 }, ];me gustaría pasar el valor de tipo al objeto imageURL para obtener la url. Sé que puedo pasarlo como img: imageURL['brakePad'] pero eso no es lo que estoy tratando de lograr. ¿Hay alguna manera de que pueda extraer el valor de la propiedad de tipo y pasarlo al objeto imageURL como clave? Gracias.
Puede usar el mapa para obtener una matriz de URL's iterar sobre la matriz de products .
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);Puede iterar sobre la matriz de productos y luego usar el valor de tipo para cada producto,
por ejemplo, usando for...of loop,
for (let product of products) { // here you have access to individual product imageURL[product.type] // brakepad, tierodend ... } o for loop convencional:
for (let i = 0; i < products.length; i++) { const type = products[i].type imageURL[type] }Si desea agregar la URL de la imagen a los objetos del producto, puede mapear sobre la matriz de productos, por ejemplo,
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) Puede leer más sobre el método de map aquí en mdn
O si desea agregar a los objetos existentes en lugar de crear una nueva matriz usando map , entonces:
for (let product of products) { product.img = imageURL[product.type] } console.log(products)