Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

324
Visualizações
If object is already in the array I want to remove the old object and add the new one

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

enter image description here

[2]: https://i.stack.imgur.com/9OQPb.png

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda