1

I tried to format a array to object. it's working fine but I need to know, Is this correct or wrong? any other standard way to do this?.

I used underscoreJS for this.

//What I get from API

"A/a/1" = A -> Category, a -> Subcategory, 1 -> child of subcategory.

["A", "A/a", "A/b", "A/a/1", "A/a/2", "B", "B/a"];

//Which format i need.

[
   {
      "name":"A",
      "parent":"",
      "children":[
         {
            "name":"a",
            "parent":"A",
            "children":[
               {
                  "name":"1",
                  "parent":"a",
                  "children":[

                  ]
               },
               {
                  "name":"2",
                  "parent":"a",
                  "children":[

                  ]
               }
            ]
         },
         {
            "name":"b",
            "parent":"A",
            "children":[

            ]
         }
      ]
   },
   {
      "name":"B",
      "parent":"",
      "children":[
         {
            "name":"a",
            "parent":"B",
            "children":[

            ]
         }
      ]
   }
]

MY CODE :

var dataObj = function(){
        this.name = "";
        this.parent = "";
        this.administrator = "";
        this.children = [];
      };


  var d_ = []; 

  _.each(data, function(item, index){

        var row = new dataObj();
        var item_array = item.split("/"),
            item_array_length = item_array.length;

          if(item_array.length  == 1){

            row.name = item_array[0];
            d_.push(row);

          } else {

              row.name = item_array[1];
              row.parent = item_array[0];
              var newC = d_[_.findIndex(d_, {name:item_array[0]})];

            if(item_array.length  == 2) {

              newC.children.push(row);

            } else if(item_array.length  == 3) {


              newC.children[_.findIndex(newC.children, {name: item_array[1]})]
                  .children.push({name : item_array[2], parent : item_array[1]});


            }


          }

  });

UPDATE The level of subcategory is not limited. "A/a/1/i/n/x/y...."

5
  • sorry but what is the logic behind that? is there anything we can apply? it doesn't really seem to have a very specific logic. Commented Apr 16, 2015 at 10:02
  • @briosheje "A/a/1" = A -> Category, a -> Subcategory, 1 -> child of subcategory. all levels was separated with "/". I need to change the format to object (i add the wanted format above.) Commented Apr 16, 2015 at 10:14
  • I can see the 'administrator' attribute absent from some of the node in the final output which you are looking for. Please clarify if this is intended and if so what should be the logic behind the same? Commented Apr 16, 2015 at 10:15
  • And would like to know other constraints and conditions like if 1. there is any possibility of duplicate elements on your response from the API 2. if the level of nesting is going to be maximum three . That will give us a clear idea if the solution should be generic enough to handle all such cases Commented Apr 16, 2015 at 10:25
  • @DopedDude don't think about administrator.. The level of subcategory is not limited. "A/a/1/i/n/x/y....". can't limit to any level ( but currently i did for 3 levels). The logic is we need to create the object form a string for generate the level of a product. Commented Apr 16, 2015 at 10:44

1 Answer 1

2

I feel your implementation can be improved. Following are the few possibilities:

  1. To reduce the processing time the return data structure of the API can be of the form ["A/b", "A/a/1", "A/a/2", "B/a"] instead of ["A", "A/a", "A/b", "A/a/1", "A/a/2", "B", "B/a"]
  2. _ library does not seem helping much, the code can be implemented in plain javaScript.
  3. The implementation can be made generic enough to handle any level of nested children. The current implementation is limited to level 3.

A simple algorithm I can think of would consist of the following high level steps:

  1. Let's call the data served from API as sampleArray.
  2. for each element of sampleArray we have currentSplittedElementArray = sampleArray[i].split('/');
  3. Let's call required output as finalOutput
  4. loop through the finalOutput and test if the element is already present finalOutput[i].name === currentSplittedElementArray[0]
  5. If the element is already present then let's loop through the currentSplittedElementArray and update the same element of the finalOutput with the elements of currentSplittedElementArray. (If the element is not already present on the finalOutput then let's first create the element on the finalOutput and populate it with the elements of currentSplittedElementArray)

I know the above algorithm may seem daunting and the steps outlined will include invoking a function repeatedly in a loop or using some sort of recursion. But this is something I would have done if I were to implement something like this.

I am open to any area of improvement/optimization in my approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.