S
S
sergey_from_saratov2018-02-08 20:26:16
JavaScript
sergey_from_saratov, 2018-02-08 20:26:16

How to keep the last 10 records in an object?

I want to write to the localstore an object in which the elements of the form are a unique key: value. So that there are no repetitions. Right now, everything is well recorded without repetition. But the question arose, how can I make sure that only the last 10 added emails remain in my object? I read somewhere that through Set, but did not understand where to insert it.

$( "#toFavorites" ).click(function() {
  
  alert( "Товар добавлен в избранное" );
  
  /*ID товара*/
  var code = itemInfo.PROPERTIES.KODSITE.VALUE;
  
  /*Берём массив товаров из памяти*/
  var favoritesItems = JSON.parse(localStorage.getItem('favoritesItems'));
  
  
  /*Если пользователь заходит первый раз*/
  if(!favoritesItems){
    console.log("favoritesItems пустой");
    favoritesItems = {};
  }
  
  favoritesItems[code] = itemInfo;
  console.log(favoritesItems);
 
  /*Регулируем кол-во товаров в памяти (10 последних добавленных)*/

  
  /*Пишем результат в память*/
  localStorage.setItem('favoritesItems', JSON.stringify(favoritesItems));

});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2018-02-08
@Stalker_RED

As far as I understand, you have some data in your favoritesItems, and the product ID (code) is the key.
In that case, what is the "last 10 entries"? How to determine which of them are "last", if the time of adding from to the list is not recorded anywhere? Of course, you can take the last 10, when sorting by the code key, will that suit you?
favoritesItems = favoritesItems.slice(-10)

M
Morph1nskij, 2018-02-08
@Morph1nskij

As far as I understood the question correctly, you need to create your own data structure based on an array with a dimension of 10 elements (something like a queue, when a new element is added, it becomes the last one, and the first one is removed and the elements are checked for uniqueness) and use it.

A
Alexander Kositsyn, 2018-02-09
@alex_keysi

so that there are no repetitions, this is a set object.
To set the time for adding a product, write the time to the saved product using new Date().
and then put a filter when adding a product
like this filter
for (let i=0; i<10: ++i){
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question