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

113
Vistas
JS Object append and only add new value to the first object

I have 2 objects, and I want to add a new key value pair to only the first match object of it's kind.

Obj1
[{
buyDate: "yesterday",
productId: "0001",
consumerId: "John",
price: 10
// add new key value pair here
},
{
buyDate: "today",
productId: "0001",
consumerId: "John",
price: 10
},
{
buyDate: "yesterday",
productId: "0002",
consumerId: "Doe",
price: 7
}]
Obj2
{
productId: "0001",
consumerId: "John",
quantity: 4
}

In Obj1, since the productId and the consumerId are the same, I want to add a new key value pair from Obj2 that has the same productId and consumerId to the first 0001 and John.

I got stuck from here.

     let newObj2 = {};
      if (Obj1) {
        Obj1.forEach((e) => {
          newObj2[e.consumerId] = e;
        });
      }

      let newData = Obj1.map((e) => {
        return {
          ...e,
          quantity: Obj2[e.consumerId]?.quantity
            ? Obj2[e.consumerId]?.quantity
            : 0,
        };
      });

Could anyone give me some help how to achieve that? Appreciate any kinda response. Thanks before

edit: since it's a dummy data I wrote some mistake

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

0

Use Array.find to find the item in the array being searched like so:

const obj1 = [
  { buyDate: "yesterday", productId: "0001", consumerId: "John", price: 10 },
  { buyDate: "today", productId: "0001", consumerId: "John", price: 10 },
  { buyDate: "yesterday", productId: "0002", consumerId: "Doe", price: 7 }
];
const obj2 = {
  productId: "0001", consumerId: "John", quantity: 4
};
let item = obj1.find(function(item) {
  return item.productId === obj2.productId && item.consumerId === obj2.consumerId
});
if (item === undefined) {
  // not found
} else {
  item.quantity = obj2.quantity;
}
console.log(obj1);

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