Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda