var items = {}; $('.shop-one').each(function () { var clicks = $(this).find('.add_shop_content'); if(clicks.data('clicks')){ var count = $(this).find('input').val(); var id = $(this).children('input').val(); items['id'] = id; items['count'] = count; } }); 

In this case, the array overwrites, and how to make it add new values?

  • Where in the above code is an array? where should the values ​​be added? - Grundy
  • items with id and count keys - Alexander Reizan
  • To add new values, you need to add new properties, you now give the id property the id value, and the count count property the value. - user190134
  • items - This is an object, the keys in the object are unique. Therefore, it is impossible to make several identical keys in any way - Grundy

1 answer 1

If I understood your task correctly, then you need to make items not an object but an array, which, later, will hold objects with id and count properties.

Therefore, we rewrite var items = {}; on

 var items = []; 

Now we have the standard methods and functions of the array in js and we can use push add an object with the properties we need to the array

 items.push({id: id, count: count}); 

Your code is off the shelf.

 var items = []; $('.shop-one').each(function () { var clicks = $(this).find('.add_shop_content'); if(clicks.data('clicks')) { var count = $(this).find('input').val(); var id = $(this).children('input').val(); items.push({id: id, count: count}); }; }); 
  • Uncaught TypeError: items.push is not a function, why does it generate such an error? - Alexander Reizan
  • because you forgot to change var items = {} to var items = [] , apparently - Vyacheslav Danshin
  • @VyacheslavDanshin, try to write more detailed questions, and not just throw a piece of code without explaining what it does and what has changed. - Grundy
  • Sorry, thanks, it works. It will be necessary to read about objects and arrays - Alexander Reizan
  • ok, I 'll fix it up , just from work, distracted, so just a dry answer - Vyacheslav Danshin