如何使用* ngFor for json数组来选择值

时间:2018-02-07 08:08:20

标签: arrays json angular ionic-framework

这是我要打印的#JSON数据" 2018年1月4日"作为列表标题和描述作为列表的内容。如何使用*ngFor此数据

当我使用*ngFor="let item of timeline data"时 我收到了一个错误

cannot find a differ supporting object '[object object]' of type 'object'. ngfor only supports binding to iterables such as arrays

以下是数据:

{
    "msg": "All Timeline Data",
    "data": {
        "4th January 2018": [
            {
                "id": 294,
                "description": "1st data",
                "taken_on": "4th January 2018",
                "status": "active",
                "created_at": "2018-01-04 06:54:06",
                "updated_at": "2018-01-04 06:54:06",
                "deleted_at": null
            },

                "id": 295,
                "description": "2nd data",
                "taken_on": "4th January 2018",
                "status": "active",
                "created_at": "2018-01-04 06:54:06",
                "updated_at": "2018-01-04 06:54:06",
                "deleted_at": null
            }
          ],
     "5th January 2018": [
            {
                "id": 296,
                "description": "3rd data",
                "taken_on": "5th January 2018",
                "status": "active",
                "created_at": "2018-01-05 06:54:06",
                "updated_at": "2018-01-05 06:54:06",
                "deleted_at": null
            }
      ]
   }
}

3 个答案:

答案 0 :(得分:3)

你的“数据”不是数组,而是一个对象。

如果您更换

"data": {

"data": [

你将可以迭代日期。

另外,你似乎在{'2018年1月4日'的第二项之前失踪了:'阵列。

如果你真的需要迭代对象属性,你可以这样做。

组件:

objectKeys = Object.keys;

模板:

<div *ngFor="let key of objectKeys(timeline.data)"> {{key + ' ' + timeline.data[key]}} </div>

答案 1 :(得分:0)

将您的Object转换为数组,然后在*ngFor

中使用它

这里是working live demo

此处非常有用,如Angular 2 ngFor— Not only for Arrays

答案 2 :(得分:0)

也许尝试添加elvis运算符。 ? 以下输出应为294.

另外,正如所指出的“数据”不是数组,它是一个对象。

   <ion-list>
    <ion-item *ngFor="let item of timeline?.data?.4th January 2018>
        <p>{{item.id}}</p>
    </ion-item>
   </ion-list>