Javascript string for object reference (without eval () or indexes)

I have seen quite a few related questions and Google results, but none of them match my problem.

I get the string "header.h2" that I want to limit to " var objects ". So I want objects.header.h2 (which contains more hash data).

However, I do not want to use eval () or the often suggested buttons[] for the obvious reason that buttons[header.h2 ] will not work and I will need buttons[header][h2] .

So, how can I remain an object notation or in the worst case solve my problem?

+4
source share
2 answers

Just a quick sketch of a possible way:

Your details :

 var data = [ {foo: 1, bar: 2, foobar: [ 'a', 'b', 'c' ]}, {foo: 1, bar: 2, foobar: [ 'd', 'e', 'f' ]}, {foo: 1, bar: 2, foobar: [ 'g', 'h', 'i' ]} ]; var accessor = '1.foobar.2'; 

Using helper function :

 function helper(data, accessor) { var keys = accessor.split('.'), result = data; while (keys.length > 0) { var key = keys.shift(); if (typeof result[key] !== 'undefined') { result = result[key]; } else { result = null; break; } } return result; } 

Or make it accessible to all objects : (I personally don’t like it ...)

 Object.prototype.access = function (accessor) { var keys = accessor.split('.'), result = this; while (keys.length > 0) { var key = keys.shift(); if (typeof result[key] !== 'undefined') { result = result[key]; } else { result = null; break; } } return result; }; 

Debug output :

 console.log( helper(data, accessor), // will return 'f' data.access(accessor) // will return 'f' ); 
+8
source

I would create a "populate" method that creates an object on the dotted notation string that it sets:

 var populate = function(obj, str) { var ss=str.split(/\./), len=ss.length, i, o=obj; for (i=0; i<len; i++) { if (!o[ss[i]]) { o[ss[i]] = {}; } o = o[ss[i]]; } return obj; }; var objects = populate({}, 'header.h2'); objects.header.h2; // => Object {} populate(objects, 'foo.bar.gah.zip'); objects.foo.bar.gah.zip; // => Object {} 

Testing is required, but should bring you closer to your goal.

+3
source

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


All Articles