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

81
Vistas
How to make sure Array has object items only with unique keys

I'm creating an online store. The product has attributes (in this case, iMac computer has attributes like: capacity, usb features and digital keyboard.) I store the attributes in my state. enter image description here

The problem is, every time I switch from, for example, 256GB capacity to 512GB capacity, it adds an entire new object with {capacity:"512GB"} to the array.

How do I configure my handler function (code below) so that it conditionally checks if the object in an array already has 'Capacity' key, and updates that to a new selection, instead of adding another object? I tried everything, I'm desperate

the handler receives object with key-value pair, and the key (as label) itself, and type. In this case, type can be ignored.

const handleAttributeChange = (object, type, label) => {
      if (type == "text") {
        this.setState({
          selectedAttributes: {
            id: id,
            text: [...this.state.selectedAttributes.text, object],
            swatch: this.state.selectedAttributes.swatch,
          },
        });
      } else if ((type = "swatch")) {
        this.setState({
          selectedAttributes: {
            id: id,
            text: this.state.selectedAttributes.text,
            swatch: [...this.state.selectedAttributes.swatch, object],
          },
        });
      }
    };

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

0

Instead of an array, you can take objects with diff key values. If keys are unique. Later u can convert it into the list of values.

let obj = {};

const update = (o) => {
  obj = { ...obj, ...o };
};
   
/* In case you know key, value */
const update2 = (key, value) => {
   obj[key] = value;
};

console.log(obj);
update({ a: 1 });
update({ b: 2 });
console.log(obj); // { a: 1, b: 2 }
update({ a: 3 });
console.log(obj); // { a: 3, b: 2 }

console.log(Object.entries(obj).map(([key, value]) => ({ [key]: value })));
 //[ { a: 3 }, { b: 2 } ]

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