You need to create a document of this type.

{ "menu0":{"title":"Для нее","id":57,"cat":1}, "menu1":{"title":"Для дома","id":62, "cat":1}, } 

Trying to create so

 $("#secure").click(function (e) { e.preventDefault(); var menu $( "#sortable li" ).each(function (i) { var id = $(this).data('id'); var cat = $(this).data('cat'); var title=$(this).data('title'); //var menu={title: title, id: id, cat: cat }; var addmenu ={menu:menu} console.log(JSON.stringify(addmenu)); }); console.log(JSON.stringify(menu)); }); 

I get

 {"menu":{"title":"Для нее","id":57,"cat":1}} {"menu":{"title":"Для дома","id":62,"cat":1}} 

How correctly - I do not understand.

  • right, you need to give the name of the name of the property - Grundy

2 answers 2

The problem is that you type a string instead of adding it to an array / object. Declare a separate variable for the entire content of the "document", a separate variable for one element. For example:

 var menu = {}; $( "#sortable li" ).each(function (i) { // ... var key = 'menu' + i; var addmenu = {title: title, id: id, cat: cat }; menu[key] = addmenu; }); console.log(JSON.stringify(menu)); 

And avoid non-initialized variables, such as the menu in your example. If the selector does not return a single li, then the variable will remain uninitialized (you will see undefined or an error).

  • And if you want to get a valid JSON, then a comma after the last element is not needed. And it will be more convenient to store everything in a regular array, and not in an object. - Yury Sitnikov
  • The first argument of the anonymous function will not contain the index of the element - you must calculate it manually. - why not? Do you know something that is not in the documentation? .each (function) function Type: Function (Integer index, Element element) - Grundy
  • Sorry, confused. Corrected in the answer - Yury Sitnikov

In this case, the collection of elements is displayed on an array of objects, and the subsequent convolution of the array into an object, if you pay attention to the names of the keys, you will notice that they correspond to the indices with the prefix menu .

To map one collection to another, the map method is used followed by a call to get to get an array, not a jQuery object.

The array is needed because, in the jQuery object, there is no reduce method that will be used to minimize the object.

The code may look like this:

 var menu = $( "#sortable li" ).map((i, el)=> { id: $(el).data('id'), title: $(el).data('title'), cat: $(el).data('cat') }) .get() .reduce((resultObj, cur, i)=> { resultObj[`menu${i}`] = cur; return resultObj; }, {});