且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 .txt 文件 Javascript 创建包含 N' 个嵌套对象的嵌套对象

更新时间:2022-03-19 09:34:47

您可以使用以下代码.这个算法"还通过完全点的名称临时存储属性,作为相应嵌套对象的同义词.这样它可以快速检索到在哪里注入下一行的对象.

You can use the following code. This "algorithm" temporarily stores also properties by their fully dotted names, as synonyms for the corresponding nested objects. This way it can quickly retrieve where to inject the next line's object.

请注意,如果输入已排序,则算法执行速度最快.如有必要,您可以使用 lines.sort() 执行此操作.

Note that the algorithm performs fastest if the input is sorted. This you can do with lines.sort() if necessary.

function addNestedObject(obj, lines) {
    var map = { '': obj }; // Set starting point for empty path
    function addLine(line) {
        var name = line.split(".").pop();
        var path = line.substr(0, line.length-name.length-1);
        if (!map[path]) addLine(path); // recurse to create parent
        if (!map[line]) map[line] = map[path][name] = {}; // set name & line synonym
    }
    // Process each line with above private function.
    for (var line of lines.slice().sort()) addLine(line);
    return obj; // Might be useful to have as return value as well 
};

// Sample input
var lines = [
    'CITYS.AREAS',
    'CITYS.AREAS.STREETS',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TV',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.VASE',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.ASTREY',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.SHAMPOO',
    'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.CONTITIONER',
    'CITYS.AREAS.STREETS.HOUSES.GARDEN',
    'CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL',
    'CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL.WATER',
    'CITYS',
];

var stractureobj = { 'otherProperty': 42 };

// Convert lines to nested object and add to stractureobj
addNestedObject(stractureobj, lines);

// Output in snippet
document.querySelector('pre').textContent=JSON.stringify(stractureobj, null, 4);

<pre></pre>

上面使用了一个对象stractureobj,它已经有自己的属性,必须添加嵌套结构.

The above uses an object stractureobj, with already its own properties, to which the nested structure must be added.

如果你只对一个只有嵌套结构的对象感兴趣,没有别的,你可以用空对象调用它并分配返回值:

If you are only interested to have an object with just the nested structure, and nothing else, you could call it with the empty object and assign the return value:

var stractureobj = addNestedObject({}, lines);

归结为与此相同:

var stractureobj = {};
addNestedObject(stractureobj, lines);