从json数组获取id

时间:2017-09-20 01:27:14

标签: javascript angular typescript

我很难弄清楚如何迭代json数据来收集所有重复的Id以显示与其Id匹配的“dateTimes”。

enter image description here

例如,我需要它显示类似于: 富豪布劳沃德体育场12& RPX 2017-09-20 13:30 2017-09-20 16:00 2017-09-20 18:35

Flipper的好莱坞影院10 2017-09-20 12:40 2017-09-20 14:40 2017-09-20 16:35

我写了一个函数,我认为这只适用于一个Id,但我不知道如何找到所有匹配的Id来显示dateTimes。

getShowtimes(data){

    var json = JSON.parse(data);

    for(let i = 0; json.theater.id; i++){

        if (json[i].theatre.id == 10863){

            json[i].theatre.dateTime;

        }

    }

}

现在我没有使用该功能来显示结果(因为它不起作用),我只是使用下面的代码。

<div class="showtime" *ngFor="let shows of show">
    <div *ngFor="let detail of shows.showtimes>
        <div *ngIf="detail.theatre.id == 10863">
            {{detail.theatre.name}}{{detail.dateTime}}
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

也许这会有所帮助:

&#13;
&#13;
const data = [
    { theatre: { id: "10863", name: "Regal Broward Stadium 12 & RPX", dateTime: "2017-09-20T13:30" }},
    { theatre: { id: "10863", name: "Regal Broward Stadium 12 & RPX", dateTime: "2017-09-20T13:30" }},
    { theatre: { id: "10863", name: "Regal Broward Stadium 12 & RPX", dateTime: "2017-09-20T16:00" }},
    { theatre: { id: "10863", name: "Regal Broward Stadium 12 & RPX", dateTime: "2017-09-20T18:35" }},
    { theatre: { id: "10863", name: "Regal Broward Stadium 12 & RPX", dateTime: "2017-09-20T21:00" }},
    { theatre: { id: "4089", name: "Flipper's Hollywood Cinema 10", dateTime: "2017-09-20T12:40" }},
    { theatre: { id: "4089", name: "Flipper's Hollywood Cinema 10", dateTime: "2017-09-20T14:40" }},
    { theatre: { id: "4089", name: "Flipper's Hollywood Cinema 10", dateTime: "2017-09-20T16:35" }}
];

let result = {};

data.forEach((item) => {
  if (!result.hasOwnProperty(item.theatre.id)) {
    result[item.theatre.id] = {
        name: item.theatre.name,
        dates: item.theatre.dateTime
    };
  } else {
    result[item.theatre.id].dates = result[item.theatre.id].dates + ' ' + item.theatre.dateTime;
  }
});


Object.keys(result).forEach((key) => {
  console.log(`${result[key].name} ${result[key].dates}`)
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

像这样使用 detail.theatre.id === '10863' ,因为它是一个字符串,

<div *ngIf="detail.theatre.id === '10863'">
    {{detail.theatre.name}}{{detail.dateTime}}
</div>