Home > Software engineering >  How to make sure Array has object items only with unique keys
How to make sure Array has object items only with unique keys

Time:10-17

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],
          },
        });
      }
    };

CodePudding user response:

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 };
};

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 } ]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related