I have array of objects and when user select an option it adds an object into the array I want to write a code to check if this object key is already in one of the objects in the array to replace the old one with the new object the user selected from the provided option enter image description here
which mean this array can't have two object with the same key such as
iMac 2021-Touch ID in keyboard
any solutions I am stuck here
edit:
attribute.items.map((item, index2) => {
return (
<div key={index2}>
<input
onChange={this.handleChange}
type="radio"
name={`${this.props.currentItem.name}-${attribute.name}`} value={item.value}
/>
</div>;
when user selecet option from one of these attributes it's added to an array which will be send to the cart with the item
handleChange = (e) => {
const { name, value } = e.target;
this.setState((prevState) => ({
selectedAttribute: [
...prevState.selectedAttribute,
{ [name]: value }
],
}));
};
I am trying to do something like this to prevent adding two or more object for the same attribute
let alreadyAdded = this.state.selectedAttribute.some((element) => this.state.selectedAttribute.indexOf(element) !== -1);
if user select the attributes from the first time there will be no problem else if user decided to change the attribute it will be added with the new value without removing the old one, the array of attributes will have more values than it should which will cause an error
as you will see in this picture
You can use array find or findIndex method and object hasOwnProperty something like that:
const items = [
{ key1: value1 },
{ key2: value2 },
];
const neededKey = 'key1';
const item = items.find((item) => item.hasOwnProperty(neededKey));
find: then, if found - update, else insert
findIndex: then, if found - splice, else insert
but if in your case only 1 key is used in every item, why not just using object like:
const items = {
key1: value1,
key2: value2,
}
and update it directly?
if this is react state, you can use something like:
setState({
...oldState,
[neededKey]: neededValue,
})
to update your state