2016-08-21 116 views
0

我想要一本字典轉換爲使用字符串angular2是否有angular2的流lambda表達式?

,如:key1=value1&key2=value2&...

有什麼辦法來創建像java8流作用?或者一個優雅的方式?

這是我的嘗試:

mapToFormParamsString(dict : any) : string{ 
    var a = []; 
    for (var key in dict) { 
     if (dict.hasOwnProperty(key)) { 
      a.push(key+"="+dict[key]); 
     } 
    } 
    return a.join("&"); 
} 
+0

不要忘記'encodeURIComponent'! – Bergi

+0

'Object.keys(dict).map(key => ...).join(「&」)'應該讓你去。 – Bergi

+0

'Object.keys(dict).map(k => encodeURIComponent(k)+「=」+ encodeURIComponent(dict [k])).join(「&」)' – Thomas

回答

1

這或Array#reduce

mapToFormParamsString(dict : any) : string{ 
    return Object.keys(dict).reduce(function(rv, key) { 
     return rv + "&" + key + "=" + dict[key]; 
    }, "").substring(1); 
} 

或者你使用打字稿(或ES2015 +):

mapToFormParamsString(dict : any) : string{ 
    return Object.keys(dict).reduce((rv, key) => rv + "&" + key + "=" + dict[key], "").substring(1); 
} 

喜歡你的,那隻處理自己的屬性名稱。

+0

我認爲這會在開始。 –

+0

@AsadSaeeduddin:注意'.substring(1)'末尾。 –

+0

啊,好點。你真的需要'+ ='嗎? 'reduce'只關心回報價值。 –