'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



Solution 1:[1]

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");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shivam Sharma