2015-02-11 4 views
0

Учитывая данные объекта, я хочу рекурсивно структурировать его так, чтобы он выглядел как structuredObj. У меня есть s1 до sN. Я только определил s2, чтобы начать.Структура объекта с использованием рекурсии

Это вход:

    var data { 
         ... 

         "s2": true, 
         "s2a": true, 
         "s2b": true, 
         "s2c": true, 
         "s2d": true, 
         "s2e": true, 
         "s2f": true, 
         "s2fa": true, 
         "s2fb": false, 
         "s2g": true, 
         "s2h": true, 
         "s2ha": false, 
         "s2hb": true, 
         "s2i": true, 
         "s2ia": false, 
         "s2j": true, 
         "s2k": true, 
         "s2l": true, 
         "s2m": true, 
         "s2n": true, 
         "s2o": true 

         ... 
        } 

Это выход:

var structuredObj = { 
      "s2": { 
      "situation": "The client owns a property.", 
       "a": true, 
       "questions": { 
       "a": { 
        "q": "A. Does the court order permit the deputy to sell the property?", 
         "a": true 
       }, 
       "b": { 
        "q": "B. Is the client a resident in the property?", 
         "a": true 
       }, 
       "c": { 
        "q": "C. Is the spouse of the client a resident in the property?", 
         "a": true 
       }, 
       "d": { 
        "q": "D. Is a dependant of the client a resident in the property?", 
         "a": true 
       }, 
       "e": { 
        "q": "E. Is the property being maintained?", 
         "a": true 
       }, 
       "f": { 
        "q": "F. Is the property being rented out?", 
         "a": true, 
         "questions": { 
         "a": { 
          "q": "a) Is an appropriate income being received?", 
           "a": true 
         }, 
         "b": { 
          "q": "b) Is there a rental agreement in place?", 
           "a": false 
         } 
        } 
       }, 
       "g": { 
        "q": "G. Is there an appropriate insurance policy in place?", 
         "a": true 
       }, 
       "h": { 
        "q": "H. Does the client have any valuables in the property?", 
         "a": true, 
         "questions": { 
         "a": { 
          "q": "a) Are the valuables secure?", 
           "a": false 
         }, 
         "b": { 
          "q": "b) Have details of the valuable been reported to the OPG?", 
           "a": true 
         } 
        } 
       }, 
       "i": { 
        "q": "I. Does the client require care?", 
         "a": true, 
         "questions": { 
         "a": { 
          "q": "a) Are the client’s care costs being met?", 
           "a": false 
         } 
        } 
       }, 
       "j": { 
        "q": "J. Is there a charge against the property?", 
         "a": true 
       }, 
       "k": { 
        "q": "K. Is the deputy considering selling the property?", 
         "a": true 
       }, 
       "l": { 
        "q": "L. Is the property jointly owned?", 
         "a": true 
       }, 
       "m": { 
        "q": "M. Has the Deputy been asked to take action previously?", 
         "a": true 
       }, 
       "n": { 
        "q": "N. Is there a history of risk on the case?", 
         "a": true 
       }, 
       "o": { 
        "q": "O. Have any other risks to the client been identified?", 
         "a": true 
       } 
      } 
     } 



        // Something like this: 
        structuredObj = structureMyFlatObject(data); 

Это функция, которая принимает входные данные и структуры его.

  structureData: function (data) { 

       var i=0, 
        situationNum, 
        previousSituationLetter, 
        situationLetter, 
        situationalChildLetter, 
        label = 'LABEL.NAME', 
        structuredObj = {}, 
        keys = Object.keys(data); 

       for(; i<keys.length; i++) { 

        situationNum = keys[i].substring(0,2); // s1 - s28 
        situationLetter = keys[i].charAt(2); // a - z 

        if(keys[i].length === 4) { 

         situationalChildLetter = keys[i].charAt(3); // a - z 

         if(!structuredObj[situationNum].questions[previousSituationLetter].questions) { 
          structuredObj[situationNum].questions[previousSituationLetter].questions = {}; 
         } 

         structuredObj[situationNum].questions[previousSituationLetter].questions[situationalChildLetter] = { 
          "q": $translate.instant(label + keys[i].toUpperCase()), 
          "a": data[keys[i]] 
         }; 

         continue; 
        } 

        //Does the property start with s1, s2, s3, .., .., s28 
        if(keys[i].indexOf(situationNum) === 0) { 

         if(structuredObj[situationNum]) { 
          structuredObj[situationNum].questions[situationLetter] = { 
           "q": $translate.instant(label + keys[i].toUpperCase()), 
           "a": data[keys[i]] 
          }; 
         } else { 
          structuredObj[situationNum] = {}; 
          structuredObj[situationNum].situation = $translate.instant(label + keys[i].toUpperCase()); 
          structuredObj[situationNum].a = data[keys[i]]; 
          structuredObj[situationNum].questions = {}; 
         } 
        } 

        previousSituationLetter = situationLetter; 
       } 

       return structuredObj; 
      }, 

Это работает для данного конкретного случая использования, но мне нужно, чтобы он работал для всех, например s1-s28. В настоящее время эта функция взрывается, например, при нажатии s10fa. Я надеялся на рекурсивное решение, поскольку оно начинает запутываться.

Благодаря

+0

Пожалуйста, покажите нам, что вам удалось написать, иначе мы не сможем вам помочь. – Bergi

+0

В соответствии с запросом :-) – user3034151

ответ

0

Почему бы не пойти на бинарном дереве, как структура, но вместо этого только два узла, имеют х-количество Iterable узла и просто перебирать каждого из них, и сделать Somthing, чтобы определить, если это будет вопрос или новый объект Я.

Изменить: Я имел в виду, как это:

var max_depth = 4; 
 
    var current_depth = 0; 
 

 
    function n(){ 
 
     return {}; 
 
    } 
 

 
    function random_object(obj) { 
 
     if (obj == null) { 
 
      temp = {}; 
 
      var end = Math.floor((Math.random() * 10) + 1); 
 
      for (i = 0; i < end; i++) { 
 
      temp[String(i)] = null; 
 
      } 
 
      return temp; 
 

 
     } else { 
 
      for (var key in obj) { 
 
       if((Math.random() * 10) < 5){ 
 
       obj[key] = "This is element " + key + " of depth " + current_depth 
 
       }else{ 
 
       if(current_depth < max_depth){ 
 
        current_depth = current_depth + 1 
 
        obj[key] = random_object(random_object()); 
 
       }else{ 
 
        obj[key] = "This is element " + key + " of depth " +  (current_depth + 1) 
 
       } 
 
       } 
 
      } 
 
      current_depth = current_depth - 1 
 
      return obj; 
 
     } 
 
    } 
 
    console.log(random_object(random_object()));

рекурсивно генерирует объект случайного х количества атрибутов, которые каждый из них может быть либо строкой (вопрос) или другой объект случайного х-количества атрибутов

+0

Нет, он должен быть написан в javascript, преобразован в json, а затем поверх провода. – user3034151

+0

Спасибо за ваш ответ, однако, вы не ответили на мой вопрос. Вход должен быть данными (как я опубликовал). Я не контролирую это. Опять же, структура должна выглядеть так, как я опубликовал. Между ними нет. Благодарю. – user3034151

+0

Я не делаю вашу работу за вас, я показываю пример использования рекурсивной функции для создания объекта. Вам нужно решить, как форматировать данные и рекурсивно строить их в объекте. Я дам вам подсказку, вам нужно выяснить, где происходит утверждение if, которое имеет только два возможных ответа; тот, который либо устанавливает значение, либо значение, которое приводит к рекурсивной функции, возвращающей объект. Однако объект в вашем примере не имеет согласованности (оба «вопросы» и «f» являются вложенными объектами »), поэтому я не могу судить о том, что поместит значение и что вызовет функцию. – Thermatix