代码之家  ›  专栏  ›  技术社区  ›  Kim T

角度滤波器对象

  •  0
  • Kim T  · 技术社区  · 6 年前

    用模式角度过滤JSON提要的最佳方法是什么?我之所以要这样做是为了减少使用传输状态API存储在HTML页面中的数据量。

    理想世界我想定义一个接口,并且只使用那些字段。但是接口只在编译时使用,而不是运行时。

    所以目前已经使用:

    export const FieldWhitelist = {
      'slug': true,
      'title': true,
      'type': true,
    };
    
    get(url): Observable<any> {
        return this.http.get(url).pipe(
          map(items => {
            if (typeof items === 'object') {
              Object.keys(items).forEach(field => {
                if (!FieldWhitelist[field]) {
                  delete items[field];
                }
              });
            } else if (typeof items === 'array') {
              Object.keys(items).forEach(item => {
                Object.keys(items[item]).forEach(field => {
                  if (!FieldWhitelist[field]) {
                    delete items[item][field];
                  }
                });
              });
            }
            return items;
          })
        );
    }
    

    这将打开JSON提要:

    {
      'id': '12x324jh34',
      'metadata': 'sajhjksadhjkdsa'
      'slug': 'home',
      'title': 'Homepage',
      'type': 'page',
    }
    

    在这方面:

    {
      'slug': 'home',
      'title': 'Homepage',
      'type': 'page',
    }
    

    是否有更好的方法递归筛选JSON提要以匹配模式?

    1 回复  |  直到 6 年前
        1
  •  1
  •   baao    6 年前

    你可以定义一个类和映射 items 在里面,还课

    const obj = {
      'id': '12x324jh34',
      'metadata': 'sajhjksadhjkdsa',
      'slug': 'home',
      'title': 'Homepage',
      'type': 'page',
    }; 
    
    class Data {
      slug: string;
      title: string;
      type: string;
    
      constructor({slug, title, type}: {slug: string, title: string, type: string}) {
        this.slug = slug;
        this.title = title;
        this.type = type;
      }
    }
    
    console.log(new Data(obj));
    

    还要确保知道什么 项目 在这里,你不需要检查它是一个数组还是一个对象imho,应该从返回的部分中清除。

     map(items => {