Created a multidimensional array on jQuery:

var shed = {}; shed['half-round'] = { '2100': { '2500': { 'wo-polycarbonate':16300, 'polycarbonate':21300 }, '3000': { 'wo-polycarbonate':17900, 'polycarbonate':22900 }, '3500': { 'wo-polycarbonate':21600, 'polycarbonate':26600 }, '4000': { 'wo-polycarbonate':22700, 'polycarbonate':27700 }, '4500': { 'wo-polycarbonate':24800, 'polycarbonate':29900 }, '5000': { 'wo-polycarbonate':25900, 'polycarbonate':31000 }, '5500': { 'wo-polycarbonate':27600, 'polycarbonate':32700 }, '6000': { 'wo-polycarbonate':28700, 'polycarbonate':39300 } } } 

Does jQuery know how to select data and how many elements are in each element? For example - I want to know how many elements in the element 2100, I request length - it is reported that no such function was found.

It seems that only the "until the very last tail" sampling algorithm works, for example:

 alert(shed['half-round'][2100][2500]['wo-polycarbonate']); 

which gives the farthest branch value = 16300 ...

View requests:

 shed['half-round'][2100][2500].length shed['half-round'][2100].length shed.length shed['half-round'][2100][0] shed['half-round'][0] 

Somehow difficult to implement?

I use jquery 2.1.4.

PS: like people compares JSON with the XML format and proves that it is absolutely possible to use it.

  • What does it have to do with jquery and json? - Pavel Mayorov
  • Do not confuse JSON and javascript objects, although these are very similar things, but still they are slightly different. A javascript object has such an abstruse thing as prototype inheritance, and you cannot just take and calculate the length. - andreymal
  • Look at this function here: Object.keys() - Pavel Mayorov
  • one
    Acquainted with your own answer. You yourself understand what needs to be done, why it is needed and what should happen? I propose to close the question. The author can familiarize himself with the javascript website learn.javascript and then create a new, more constructive question. - Andrew B

2 answers 2

Generally, you want strange.

For a start, this is not an array (there are no arrays in the question at all) and not even something from JSON, but just a JavaScript object with all its pluses and minuses, as well as prototype inheritance. jQuery is nowhere else, it is pure JavaScript.

In normal situations, it is extremely rare to find out the number of keys of an object (aka dictionary aka hash table): keys are simply addressed, or they are looped through, that's all. You should consider using arrays instead.

If you need to store objects in a strictly ordered manner, then you should definitely replace this all with arrays, because ordinary dictionaries / hash tables store everything out of order by definition, in any implementation of any programming language (except php, lol). (There are unusual things like OrderedDict in Python, but this is not about them.)


Still, if you carefully read and reread what is written above, and nevertheless decided to continue using js-objects, then I rolled the recursive function that allows you to find out the number of keys in the object itself and in all the descendants of the object. (There is a little extra code for outputting the log to the page; I hope you can adapt the function to your needs. If you don’t need a recursive calculation of all-all descendants, then remove those parts of the function that is related to kidsLength .)

 function calcLength (obj, printPrefix) { // printPrefix нужен только для красивого вывода на страницу printPrefix = printPrefix || ''; var length = 0; // Количество непосредственных потомков var kidsLength = 0; // Количество всех-всех потомков // Перебираем все ключи объекта for (var key in obj) { if (!obj.hasOwnProperty(key)) { // Так как может быть прототипное наследование, // не все ключи могут принадлежать непосредственно объекту // То, что принадлежит прототипам, пропускаем continue; } length += 1; kidsLength += 1; // Если потомок — тоже объект, то рекурсивно считаем // число потомков и у него if (typeof obj[key] == "object") { kidsLength += calcLength(obj[key], printPrefix + '/' + key)[1]; } } log.appendChild(document.createTextNode( printPrefix + ": непосредственных потомков " + length + ", всего потомков " + kidsLength + "\n" )); // Возвращаем вызывающему информацию о числе потомков return [length, kidsLength]; } var shed = {}; shed['half-round'] = { '2100': { '2500': { 'wo-polycarbonate':16300, 'polycarbonate':21300 }, '3000': { 'wo-polycarbonate':17900, 'polycarbonate':22900 }, '3500': { 'wo-polycarbonate':21600, 'polycarbonate':26600 }, '4000': { 'wo-polycarbonate':22700, 'polycarbonate':27700 }, '4500': { 'wo-polycarbonate':24800, 'polycarbonate':29900 }, '5000': { 'wo-polycarbonate':25900, 'polycarbonate':31000 }, '5500': { 'wo-polycarbonate':27600, 'polycarbonate':32700 }, '6000': { 'wo-polycarbonate':28700, 'polycarbonate':39300 } } }; calcLength(shed, "shed"); 
 #log { white-space: pre-wrap; font-size: 8pt; font-family: monospace; } 
 <div id="log"></div> 

  • I do not want something strange, namely, to move along the array not only horizontally, but also vertically .... Thanks for the answer, I will try to study your vision - 095
  • @ 095 are not arrays, they are javascript objects. But anyway, you can always move along it to an arbitrary depth recursively in the image and likeness of my example (in general, almost in any programming language you can). But with the length specifically in javascript, the “length” of the object is a concept that is too ambiguous (read the textbooks to understand why it is ambiguous), so it must be considered independently, as in my function - andreymal

There is no simple answer, because Object. And that every object in JavaScript occurs, includes many attributes automatically, and the exact set of attributes you receive depends on the particular translator and what code is executed before yours.

This way you can calculate exactly the attributes you need.

Here is one way:

 var foo = {"key1": "value1", "key2": "value2", "key3": "value3"}; Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted var count = 0; for (var k in foo) { if (foo.hasOwnProperty(k)) { ++count; } } alert("Found " + count + " properties specific to foo"); 

The second line shows how other code can add properties for all Object derivatives. If you remove the hasOwnProperty () check inside the loop, the number of real estate will go at least to 4. On a page with other JavaScript besides this code, it may be higher than 4 if this other code also changes the Object prototype.

You can also search in another way http://api.jquery.com/jquery.each/

 `$.each(object, function( index, value ) { //object[index]; //value; });` 
  • did I understand correctly - that this cycle only affected the first level of a multidimensional array? How to deal with the rest of the branches? - 095
  • {"key1": "value1:" value11 "," value12 "," key2 ":" value2 "," key3 ":" value3 "} - 095
  • _________________ here is the problem, I can not enter to another level .... joxi.ru/E2pb1edhBRg8Nr.jpg - 095
  • You can iterate in another way api.jquery.com/jquery.each $.each(object, function( index, value ) { object[index]; }); - ShiRO KRED
  • Here is a table to be processed: - 095