简体   繁体   English

如何确保 Array 具有仅具有唯一键的对象项

[英]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.产品具有属性(在这种情况下,iMac 计算机具有以下属性:容量、USB 功能和数字键盘。)我将这些属性存储在我的状态中。 在此处输入图片说明

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.问题是,例如,每次我从 256GB 容量切换到 512GB 容量时,它都会向数组添加一个全新的对象{capacity:"512GB"}

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.处理程序接收带有键值对的对象、键(作为label )本身和类型。 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.您可以使用具有 diff 键值的对象来代替数组。 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 } ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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