【问题标题】:Angular 8 : How Filter JSON data in localStorageAngular 8:如何在 localStorage 中过滤 JSON 数据
【发布时间】:2020-03-26 20:04:57
【问题描述】:

我在 Angular 8 项目中工作,我在 localStorage 中存储了一些数据,我需要对其进行过滤,我不确定我必须使用哪种方法。

这是 localStorage 值的外观:

[{id: 9, designation: "spectacle + restaurant", gift: [], type: "Soirée Bon plan",…},…]
0: {id: 9, designation: "spectacle + restaurant", gift: [], type: "Soirée Bon plan",…}
amount: 60
banner: ""
designation: "spectacle + restaurant"
format: "bb"
gift: []
icon: "/uploads/fe633f32ab883aae44f154f3fead6982.png"
id: 9
qte: 2
type: "Soirée Bon plan"
1: {id: 10, designation: "spectacle + restaurant", gift: [], type: "Soirée Détente",…}
amount: 80
banner: ""
designation: "spectacle + restaurant"
format: "A4"
gift: []
icon: "/uploads/9b44814145c711307c718cdaf87dc4e2.png"
id: 10
qte: 2
type: "Soirée Détente"
2: {,…}
placesListContent: [{tr_id: "628215", tr_sp_id: "12055", tr_entite: "AG", tr_cat_ordre: "1", tr_cat: "Tarifs :",…}]
qte: 1
restaurant: null
spectacle: {sp_id: "12055", sp_date: "1551737475", sp_th_id: "1264", sp_cat_id: "3", sp_prod_id: "0",…}
3: {,…}
placesListContent: [,…]
qte: 1
restaurant: null
spectacle: {sp_id: "7903", sp_date: "1448480535", sp_th_id: "1254", sp_cat_id: "6", sp_prod_id: "1481",…}

我只需要获取代表“GiftType 对象”的元素(这里是第一个和第二个元素),我用这个函数得到了它:

addGiftToCard(type) {
    type = type.type
    let cardParse = JSON.parse(localStorage.getItem('cart')) || []
    let index = _.findIndex(cardParse, item => item.type && item.id == type.id)
    if (index == -1) {
      type.qte = 1
      cardParse.push(type)
    } else {
      cardParse[index].qte += 1
    }
    localStorage.setItem('cart', JSON.stringify(cardParse))

  }

前两个元素必须通过“qte”属性过滤和分隔

【问题讨论】:

    标签: arrays json angular filter collections


    【解决方案1】:

    如果您的json 看起来像这样,那么您可以使用filter 方法在现有的gifttype 属性上进行检查:

    let arr = [
      {id: 9, designation: "spectacle + restaurant", gift: [], type: "Soirée Bon plan"},
      {id: 10, designation: "spectacle + restaurant", gift: [], type: "Soirée Bon plan"},
      {id: 11, designation: "spectacle + restaurant"}
    ]
    
    const result = arr.filter(a => a.gift && a.type);
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 2020-11-14
      • 1970-01-01
      • 2016-10-24
      • 2019-07-22
      相关资源
      最近更新 更多