Scrolling through nested objects using jQuery

Hi everyone, I am trying to find the most dynamic way to loop through an array and return certain values, return certain values ​​... json is deeply structured and can change, maybe the $ .each () formula can help?

Example:

var myobj = { obj1: { key1: 'val1', key2: 'val2' }, obj2: { key1: '2val1', key2: { nest1: 'val1', nest2: 'val2', nest3: 'val3' }, key3: { nest1: 'K3val1', nest2: 'K3val2', nest3: [ { nest1: 'val1', nest2: 'val2', nest3: 'val3' }, { nest1: 'val1', nest2: 'val2', nest3: 'val3' } ] } }, obj3: { key1: 'dddddval1', key2: 'val2' } } 

Now we can say that I want to get the value " K3val2 ", but instead of hard coding it looks like this: myobj.obj2.key3.nest2 is there a dynamic way that I do using $.each() mybe?

+4
source share
1 answer

You can just $.each calls in $.each :

Live example | Live source

 // Loop the top level $.each(myobj, walker); function walker(key, value) { // ...do what you like with `key` and `value` if (value !== null && typeof value === "object") { // Recurse into children $.each(value, walker); } } 

If you want to know how deep you are, you can also do this:

Live example | Live source

 var path = ""; // Loop the top level $.each(myobj, walker); function walker(key, value) { var savepath = path; path = path ? (path + "." + key) : key; // ...do what you like with `key` and `value` if (value !== null && typeof value === "object") { // Recurse into children $.each(value, walker); } path = savepath; } 
+17
source

Source: https://habr.com/ru/post/1490468/


All Articles