如何在Javascript函数中返回动态(键,值)对

时间:2018-08-23 16:14:06

标签: javascript angular typescript

我正在尝试编写一个将返回动态键值对的函数。

服务:

getContentfulEntries(query: QueryEntries, keyQuery?: QueryFilters[]): Observable<any> {
    const buildQuery = (obj) => {
      const propName = obj.inequality ? obj.key : obj.key + '[ne]';
      const propValue = obj.value.join(', ');
      console.log('test', propName, propValue);
      return { [propName]: propValue  };
    };
      const contentEntries = this.client.getEntries(Object.assign(query, buildQuery(keyQuery)));
    return from(contentEntries).pipe
      (map ((res: any) => res.items));
  }

控制器:

export class AppComponent implements OnInit {
  title = 'Setup Environment';
  private entriesSubscription: Subscription;

  queries: QueryEntries = {
    content_type: 'product'
  };
  keyQueries = [
    {
      key: 'sys.type',
      value: ['Entry'],
      inequality: true
    },
    {
      key: 'sys.id',
      value: ['2zqB3mZMaQOm0uIyIAus8w'],
      inequality: true
    }
  ];

  constructor(private contentfulService: ContentfulService) {
  }

  ngOnInit() {
    console.log(this.queries, this.keyQueries);
    this.contentfulService.getContentfulEntries(this.queries, this.keyQueries)
      .subscribe(res => console.log('ContentfulEntries::', res));
  }
}

界面:

export interface QueryFilters {
  key: string;
  value: string;
  minrange?: number;
  maxrange?: number;
  inequality: boolean; /*Need to specify a content_type in order to use this*/
}

因此在我的最终控制器中,在查询中我得到了键:“ sys.type”和值:“ Entry”。但我希望它返回“ sys.type”:“ Entry”。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

像这样创建对象

let propName = keyQuery.key + '[ne]';
let propValue = keyQuery.value;

const obj = { [propName]: propValue };

功能代码部分。我还对您的代码进行了一些重构

getContentfulEntries(query: QueryEntries, keyQuery?: QueryFilters): Observable<any> {

      let propName = keyQuery.key + '[ne]';
      let propValue = keyQuery.value;

      const obj = { [propName]: propValue };

      const contentEntries = this.client.getEntries(Object.assign(query, obj));
      return from(contentEntries).pipe(map ((res: any) => res.items));

}