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

263
Visualizações
How to find if an object exist in an array [array is coming from localstorage]

I created an empty array in localStorage

localStorage.setItem('items', JSON.stringify([]))

and then fetching that empty array like this :

let fetchedItems = JSON.parse(localStorage.getItem('items'));

After fetching the Array I want to append some objects in the same.

Array of Objects

let objects = [
  {
     id: '37f60b13-bb3a-4919-beff-239207745343',
     body: '1',
  },
  {
     id: '26c5b0fa-b15f-4a50-9a56-5880727a8020',
     body: '2',
  },
  {
     id: '37f60b13-bb3a-4919-beff-239207745343',
     body: '1',
  },
];

The first and last object have same id

Right now what I am doing is, as I don't want to save or append duplicate objects (by id key) in array/localstorage:

function saveItemsInLocalStorage(item) {
  let items;

  if (localStorage.getItem('items') === null) {
    items = [];
  } else {
    items = JSON.parse(localStorage.getItem('items'));
  }

  items.push({
    id: item.id,
    body: item.body,
  });

  localStorage.setItem('items', JSON.stringify(items));
}

objects.forEach((object) => {
  fetchedItems.forEach((fetchedItem) => {
    if (fetchedItem.id !== object.id) {
      saveItemsInLocalStorage(object)
    }
  });
});

The above code is not working. I have also tried reduce method.

Note initially array is empty

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

0

Let us take an example and try understanding , how you can do it with your code :

let obj = {name:"user",id:1};
let arr = [{name:"user",id:2},{name:"user",id:3}];
let present = false ;
arr.map(val=>{
   if(JSON.stringify( {...val})===JSON.stringify({...obj}) )
      present = true ;
})
if(present)console.log("The object is present")
else console.log("The object is not present");

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