Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
¿Empujar matriz sin duplicar y cambiar el valor de propiedad del objeto en Javascript?

Tengo un objeto y estoy presionando en la matriz mientras presiono, necesito restringir el duplicado y también si hay algún cambio en la propiedad, ¿actualizar la matriz en consecuencia?

 [{ Id: "a134", Name: "Name -", Company: "001", Product :"01" quantity :1 }, { Id: "a135", Name: "Name -1", Company: "002", Product :"03" quantity :2 -----> (Previous event.target.name) }, { Id: "a135", Name: "Name -1", Company: "002", Product :"03" quantity :3 ---> (current event.target.name) } ]

si estoy ingresando a la matriz, podría haber una posibilidad de actualizar la cantidad de cómo lograr el resultado a continuación

 [{ Id: "a134", Name: "Name -", Company: "001", Product :"01" quantity :1 }, { Id: "a135", Name: "Name -1", Company: "002", Product :"03" quantity :3 ---> (current event.target.name) } ]

y ahora mi codigo es

 if(event.target.value!='') { const searchObj = this.myList.find(({ Id,Product, Company }) => Product === index); if (searchObj) { console.log('searchObj',searchObj); resultVal = { ...searchObj, quantity:parseInt(event.target.value)}; if (!this.newProductList.some(e => e.Product === resultVal.Product)) { this.newProductList.push(resultVal); } } }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Esto se resuelve mejor usando una estructura de datos diferente: use un objeto simple, con clave de Id :

 let data = { "a134": { Id: "a134" Name: "Name -", Company: "001", Product: "01" quantity: 1 }, "a135": { Id: "a135", Name: "Name -1", Company: "002", Product: "03" quantity: 2 }, };

Para actualizar/agregar no presione, pero establezca el valor de la clave de objeto. Por ejemplo:

 // Let's say we want to add/update with this object: let objToAdd = { Id: "a135", Name: "Name -1", Company: "002", Product: "03" quantity: 3 } // ...then just do: data[objToAdd.Id] = objToAdd;

Esto actualizará o "insertará". En el caso anterior, se actualizará:

 let data = { "a134": { Id: "a134" Name: "Name -", Company: "001", Product: "01" quantity: 1 }, "a135": { Id: "a135", Name: "Name -1", Company: "002", Product: "03" quantity: 3 }, };

Si alguna vez necesita el formato de matriz, simplemente haga lo siguiente:

 let arr = Object.values(data);

...pero tratar de apegarse a la matriz es una garantía para el código ineficiente. Simplemente no es la herramienta adecuada para el trabajo aquí. Debe adaptar su código para que funcione con la representación de objetos simples en todo momento. Puede iterar sobre los valores en un objeto, puede eliminar elementos de un objeto, actualizar, agregar, etc.

about 4 years ago · Juan Pablo Isaza Report

0

Creo que una matriz es el tipo de datos incorrecto. Preferiría usar un mapa .

Esto, por supuesto, solo funciona si la identificación es única, ya que es lo que se usa mejor como clave:

 const myMap = new Map([["a134",{ Name: "Name -", Company: "001", Product :"01", quantity :1 }]]);

Y luego es fácil verificar si un artículo ya está presente, antes de actualizar la cantidad o agregar un artículo nuevo.

 const id = "a134"; // or "a135" for a new entry const newItem = { Name: "Name B", Company: "002", Product :"012", quantity :1 } if(myMap.has(id)){ const item = myMap.get(id); myMap.set(id, {...item, quantity: item.quantity +1}) } else { myMap.set(id,newItem); } console.log(myMap) // Map {'a134' => { Name: 'Name A', Company: '001', Product:'01', quantity: 2 } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!