2015-03-10 3 views
0

Не удалось разобрать URL-адрес Объект url, каким бы я хотел, но новый для URL-строк понравится. Мой объект выглядит следующим образом:Правильный синтаксический анализ строки url

{mod1: "/hello/world", mod25: "/hey/jude/how/are/you"} 

и мне нужно, чтобы разобрать его во что-то вроде этого

{ 
"mod1" : {"hello" : ["world"]}, 
"mod2" : {"hey" : ["jude","how","are","you"]} 
} 

Как разобрать этот URL в объект, как так? Спасибо!

Edit: до сих пор

var parseObj = $location.search(); 

      _.each(parseObj, function(ob){ 
       console.log(ob.split()); 
      }); 

Это дает мне обратно струнам, однако я не уверен, как в настоящее время разделить их на объект, где ключ является первым элементом

+0

Пробовали ли вы что-нибудь? В чем была проблема ? –

+1

так пропустите объект и используйте split() – epascarello

+0

@dystroy застрял после .split, неуверенный, как вырезать строку в объект. Благодаря! –

ответ

1

Простой прокомментировал шаги для вас в ванильным JS:

// pass in the object to the function 
function organise(obj) { 

    // create a new object which we will return from the function 
    var obj2 = {}; 

    // loop over the object we passed in 
    for (var p in obj) { 

     // create a temporary object 
     var tmp = {}; 

     // split the value of current key/value pair into an array 
     var arr = obj[p].split('/'); 

     // set the key of the temporary object to the second element 
     // (because the first element of the array is an empty string) 
     var key = arr[1]; 

     // add the rest of the array as the value of the new key 
     // of the temporary object 
     tmp[key] = arr.slice(2); 

     // finally add the new temporary object as the value of the key 
     // of the object we want to return 
     obj2[p] = tmp; 
    } 

    // return the object from the function 
    return obj2; 
} 

organise(obj); 

DEMO

+1

Спасибо, что нашли время, чтобы комментировать, это невероятно полезно для кого-то, начинающего этот материал, как я :) –

+1

Мое удовольствие. Помогает мне лучше понять это. – Andy

0

Петля над объектом свойства, разделить значения и вставить их во второй объект.

function parse(obj) { 
 
    var out = {}, 
 
    parts; 
 
    for (prop in obj) { 
 
    if (obj.hasOwnProperty(prop)) { 
 
     out[prop] = {}; 
 
     // replace the first forward slash with nothing so the first 
 
     // element of the array is not an empty string. 
 
     parts = obj[prop].replace('/', '').split('/'); 
 
     // make the first element of the array the key and assign the 
 
     // rest of the array as the value. 
 
     out[prop][parts.shift()] = parts; 
 
    } 
 
    } 
 
    return out; 
 
} 
 

 
var obj = parse({ 
 
    mod1: "/hello/world", 
 
    mod25: "/hey/jude/how/are/you" 
 
}); 
 
// just display the object 
 
document.write('<pre>' + JSON.stringify(obj, 0, 3));

0

Как насчет этого?

var x = {mod1: "/hello/world", mod25: "/hey/jude/how/are/you"}; 

var result = {}; 

for(var i in x) { 
    var entries = x[i].split('/'); 
    var firstEntry = entries[1]; 
    var arr = []; 
    for(var j = 2; j < entries.length; j++) { 
    arr.push(entries[j]); 
    } 
    var obj = {} 
    obj[firstEntry] = arr; 
    result[i] = obj; 
} 

console.log(result); 
Смежные вопросы