Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
How do you modify object inside an array using loop in JS?
module.exports.checkoutMany = async (data) => { let tempTotalAmount = 0
data.orderDetail.forEach(async e => { 

    let price = await Product.findById(e.productId).then(product => {
        console.log(`product price from forEach: ${product.price}`)
        return product.price
    })

    console.log(`price * quantity: ${price} * ${e.quantity}`)
    
    tempTotalAmount += price * e.quantity 

    console.log(`tempTotalAmount: ${tempTotalAmount}`)
})  

// let newOrderDetail = data.orderDetail.map(async obj => {
//  if(obj.keys === price) {
//      return obj.price = 1
//  } else {
//      return obj
//  }
// })

// for(i = 0; i < data.orderDetail.length; i++) {
//  if(data.orderDetail[i].price) (
//      )
// }

console.log('newOrderDetail')
console.log(newOrderDetail)

let newOrder =  await new Order ({  
    userId: data.userId,
    orderDetail: data.orderDetail,
    totalAmount: tempTotalAmount
})

return newOrder.save().then((order, error) => {
    if(error) {
        return false
    } else {
        return order
    }
})
}

I tried to get the object property name and assign new value but it did not work.

My objective is to automate the price property by getting it from the Product Model.

As of now it is manually define inside the req.body of Postman.

Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think you can accomplish this using Array.map() like you have in your first commented out attempt:

let arr = [
    {id: 1, name: "Michael"},
    {id: 2, name: "Joe"},
]

const newArr = arr.map(obj => {
    if (obj.id === 1) {
        return {...obj, name: "John"};
    } else {
        return obj;
    }
});

console.log(newArr);

The way you have it now, you are overwriting the object, not modifying the object when obj.price = 1. You can use the spread operator to fill the new object with all the properties of the previous object, then overwrite the desired property.

You are also using awaits in the wrong places. The map function, and creating newOrder are not async tasks

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda