2

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

Pedam
  • 176
  • 12
  • 1
    `localStorage.setItem` does not automagically append arrays. It just writes the 2nd argument to the provided key (and in your current code, it's a single object, not the entire array.). Also it takes a string as second argument, you probably want to to move your stringify. – Lars Mar 13 '22 at 19:48
  • 2
    Why are you stringifying the result of `setItem` and not using the value? – Christian Vincenzo Traina Mar 13 '22 at 19:48
  • @Lars Sorry!! I messed up!! I modified the code take a look – Pedam Mar 13 '22 at 19:51
  • @CristianTraìna Check the code now – Pedam Mar 13 '22 at 19:55
  • Please check out this post to see how to remove a duplicate objects from an array of objects: https://stackoverflow.com/questions/45439961/remove-duplicate-values-from-an-array-of-objects-in-javascript – Hani Mar 13 '22 at 19:57
  • @Hani I have already search for these questions but haven't found the thing/answer. – Pedam Mar 13 '22 at 20:10
  • From the question, at this line: `localStorage.setItem('items', JSON.stringify(todos));` - what is `todos`? Why is this being stored into localStorage? @Lars point merits a repeat here: simply performing `.setItem` will not append to existing array. – jsN00b Mar 13 '22 at 20:12
  • @jsN00b it is `items` typing mistake – Pedam Mar 13 '22 at 20:14
  • Suppose the `id`s in `fetchedItems` are `1, 3, 4, 5` and those in `objects` are `2, 3, 4, 6`, the nested `forEach` loops will work like this. With `object.id` as `2` (outer `forEach`), every single `fetchedItem`'s `id` (ie, `1, 3, 4, 5`) will be checked. Since `2 !== 1`, `saveItemsInLocalStorage(2);` will execute (first time). Next, since `2 != 3`, `saveItemsInLocalStorage(2);` will execute (second time). So on & so forth. – jsN00b Mar 13 '22 at 20:24
  • @jsN00b it does work if the ids are different but as you can see I mentioned initially the array is empty so it doesn't matter what the first element goes in but if the `id` of second element is same as first. the second item should not get pushed in the `Array`. – Pedam Mar 13 '22 at 20:28
  • 1
    Are you trying to continuously add items to the array? replace the items? Or do you want to keep the array to length = 1. I'm a little confused as to why you are setting the array in localstorage to an empty array each time. Also I don't see how you plan to access or append the array without parsing it back into a JavaScript object. – Joaie Adventure Mar 13 '22 at 22:51
  • I want to keep adding items in the array! And also I am not setting the array empty!! – Pedam Mar 14 '22 at 17:47

1 Answers1

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");
  • I mentioned initially the array is empty and I can also do this without using `localStorage`. Btw thanks for the effort. – Pedam Mar 14 '22 at 18:51