2017-09-25 22 views
0

我想在angular2中顯示哈希值。我得到散列格式的響應:在angular2中顯示哈希值

[{"1":"7"},{"2":"6"},{"3":"8"},{"4":"1"}] 

「1」是user_id,「7」是其帖子的計數。我需要在表格的用戶索引頁面中顯示它。

User_Id Posts 
1  7 
2  6 

任何人都可以幫我嗎?提前致謝。

回答

0

你可能想是這樣的

data:any = [{"1":"7"},{"5":"6"},{"3":"8"},{"4":"1"}]; 
ngOnInit(){ 
this.data = this.data.map(i => { 
//we need to create a new array to store the new data. 
    let newItem = []; 
//gets the property name. So this is 1,5,3,4 
    const propertyName = Object.keys(i)[0]; 
     newItem[0]= propertyName; 
//gets the value. So this is 7,6,8,1 
     newItem[1] = i[propertyName] ; 
     return newItem; 
}) 
} 

檢查演示 https://stackblitz.com/edit/angular-rispse?file=app%2Fapp.component.ts

我不是在JavaScript好,並且必須有一個更好的方式來做到這一點。

希望這會有所幫助。

+0

我在瀏覽器console.ERROR TypeError:this.data.map不是一個函數。 –

+0

@AmitKumar可以顯示你的完整代碼嗎? – brijmcq

+0

我已添加代碼。 –

0
in component you will use the response to parse like this 
response = JSON.stringify(obj); 




<table class="table table-inverse"> 
     <thead> 
     <tr> 
      <th>#</th> 
      <th>User_Id</th> 
      <th>Posts</th> 
     </tr> 
     </thead> 
     <tbody> 
     <tr *ngFor="let resonse of responseDto;"> 
      <th scope="row">1</th> 
      <td>response['User_Id']</td> 
     </tr> 
     <tr*ngFor="let resonse of responseDto;"> 
      <th scope="row">2</th> 
      <td>response['Posts']</td> 
     </tr> 
     </tbody> 
    </table> 
+0

response = JSON.stringify(this.users_post); 我越來越類型'字符串'不可分配鍵入'郵政[]'。 –

+0

檢查兩者的類型。你可以在這裏瞭解更多關於stringify https://www.w3schools.com/js/js_json_stringify.asp –

0

您可以將user_id和post分成2個不同的數組,並使用這些數組填充表。這裏userIdArray會給你[1,2,3,4],postsArray會給你[7,6,8,1]。

var userIdArray = []; 
var postsArray = []; 
array.forEach(function(userObject) { 
    //userObject = {"1":"7"} or {"2":"6"} etc... 
    userIdArray.push(Object.keys(userObject)[0]); 
    postsArray.push(userObject[userIdArray[array.indexOf(userObject)]]); 
}); 

我沒有測試沙市的回答想知道,如果一個作品,因爲在我看來,更可行,在使用循環的條款。