gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:16:29 28 4
gpt4 key购买 nike

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

服务:

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));
}

Controller :

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));
}
}

接口(interface):

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

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

感谢任何帮助!!

最佳答案

像这样创建你的对象

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));

}

关于javascript - 如何在 Javascript 函数中返回动态(键,值)对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51990145/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com