Hello!

There is the following text:

connect.host="192.0.0" connect.user="root" base.pass="12345" log = 20 

You need to make an object of the form:

  { "connect":{ "host":"192.0.0", "user":"root" }, "base":{ "pass":"12345" }, "log":"20" } 

The text may change every time. Code that started writing:

  var data = $('#data').text(), elements = data.trim().split(" "); for(i=0;i<elements.length;i++){ var pair = elements[i].split('='), properties = pair[0], //[0]'connect.host'//[1] connect.user.. value = pair[1]; //[0]"192.0.0"//[1] root .... createObj(properties, value); } var object = {}; function createObj(properties, value){ for(i=0;i<properties.length;i++){ } } 

How to knock it all into one object?

  • and what is meant by "the text can change every time"? give an example of such a modified text - MasterAlex
  • @MasterAlex I mean the data will change. I need to make an object creation program. Those. I can create an object from this data, for example: var obj = {}; obj.connect = {host: "192.0.0", user: "root"}, but this data may not be known in advance. - PavelNET
  • @PavelNET: It is not clear what to do with such a case: connect = 1 connect.user = "root" In any case, you need to break the property by point into parts, check the existence of each of the parts, and if not, add an empty object ( {} ). - VladD February
  • @PavelNET, that is, only connect, base, log will be constant, the rest can change? - MasterAlex
  • @MasterAlex in general, yes. - PavelNET

1 answer 1

 var content = "...text..".trim().split("\n"); for(var i=0, obj = {}; i < content.length; i++) { var split_full = content[i].split("="); var s_dotted = split_full[0].split("."); for(k=1, json_string = '', json_string_end = ''; k < s_dotted.length; k++) { json_string += '{"' +s_dotted[k].trim() + '":'; json_string_end += "}"; } json_string += split_full[1].trim() + json_string_end; obj[s_dotted[0]] = MergeRecursive(JSON.parse(json_string), obj[s_dotted[0]]); } function MergeRecursive(obj1, obj2) { for (var p in obj2) { try { obj1[p] = ( obj2[p].constructor==Object ) ? MergeRecursive(obj1[p], obj2[p]) : obj1[p] = obj2[p]; } catch(e) { obj1[p] = obj2[p]; } } return obj1; } console.log(obj); 

And if we use jQuery , then the function MergeRecursive() removed and

 obj[s_dotted[0]] = MergeRecursive(JSON.parse(json_string), obj[s_dotted[0]]); 

Replace with:

 obj[s_dotted[0]] = $.extend({}, JSON.parse(json_string), obj[s_dotted[0]]);