Javascript: one-dimensional object in an ancient structure for the divider



  • Hello.
    It is necessary to provide a conclusion from the database as a multi-dimensional facility.

    var rows = [
        {
            'id' : 1,
            'type' : 'text',
            'last.body' : 'Привет',
            'last.from.id' : 55,
            'last.from.name' : 'Пользователь 1'
        },
        {
            'id' : 2,
            'type' : 'text',
            'last.body' : 'Добрый день',
            'last.from.id' : 56,
            'last.from.name' : 'Пользователь 2'
        },
    ];
    

    At this point, I've been in the forehead, but I think there's a simpler and more cosmic method of this sorting of facility. Neither should investment be limited.

    var level2 = /(\w+)\.(\w+)/i;
    var level3 = /(\w+)\.(\w+)\.(\w+)/i;
    var items = [];
    for (var index in rows) {
        items[index] = {};
        for (var key in rows[index]) {
            if ((match3 = level3.exec(key)) !== null) {
                if (!(match3[1] in items[index])) items[index][match3[1]] = {};
                if (!(match3[2] in items[index][match3[1]])) items[index][match3[1]][match3[2]] = {};
                items[index][match3[1]][match3[2]][match3[3]] = rows[index][key];
            } else if ((match2 = level2.exec(key)) !== null) {
                if (!(match2[1] in items[index])) items[index][match2[1]] = {};
                items[index][match2[1]][match2[2]] = rows[index][key];
            } else {
                items[index][key] = rows[index][key];
            }
        }
    }
    console.log(JSON.stringify(items, null, 3));
    

    He'll find out:

    [
       {
          "id": 1,
          "type": "text",
          "last": {
             "body": "Привет",
             "from": {
                "id": 55,
                "name": "Пользователь 1"
             }
          }
       },
       {
          "id": 2,
          "type": "text",
          "last": {
             "body": "Добрый день",
             "from": {
                "id": 56,
                "name": "Пользователь 2"
             }
          }
       }
    ]
    


  • Somehow:

    var row = {
        "id": 1,
        "type": "text",
        "last.body": "Привет",
        "last.from.id": 55,
        "last.from.name": "Пользователь 1"
    };
    var result = {};
    

    for (var key in row) {
    var keys = key.split(".");
    var last = keys.length - 1;
    var current = result;

    for (var index = 0; index < last; index++) {
        current = current[keys[index]] || (current[keys[index]] = {})
    }
    current[keys[last]] = row[key];
    

    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2