在Angular2中显示哈希值



我想在Angular2中显示哈希值。我正在以哈希格式得到响应:

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

" 1"是User_id," 7"是其帖子的数量。我需要在表中显示在用户索引页面中。

User_Id  Posts
 1        7
 2        6

有人可以帮我吗?预先感谢。

您可能想要这样的东西

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=papp/app.component.ts

我在JavaScript中不太好,必须有更好的方法来做到这一点。

希望这会有所帮助。

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>

您可以将User_id拆分并发布到2个不同的数组中,并使用这些数组填充表。在这里,用户流动将为您提供[1,2,3,4],而PostArray会给您[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)]]);
});

我没有测试Shashi的答案,想知道这是否有效,因为在使用循环方面对我来说似乎更可行。

最新更新