简体   繁体   中英

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. 在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM