映射特定对象数组类型的数据数组

问题描述 投票:1回答:1

也许是一个简单的问题,但我找不到这方面的例子。

这是我的HttpClient调用

getItems(dataSourceUrl: string, bindKey: string, bindValue: string): Observable<SelectItem[]> {
    return this.httpClient.get<Array<any>>(dataSourceUrl);
}

我想基于bindKeybindValue将列表结果映射到SelectItem []。我怎么做?

我试过这样的事

return this.httpClient.get<Array<any>>(dataSourceUrl).pipe(map(x=> { return { label: data.bindKey, value: data.bindValue } }));

接口

export interface SelectItem {
    label: string;
    value: any;
}

两个不同的api响应的示例

1.

{key:'Istanbul', value: 'Test' }
{key:'London', value: 'Test' }

bindKey将是key bindValue将是value

2.

{name:'Istanbul', id: 'Test' }
{name:'Istanbul', id: 'Test' }

bindKey将是id bindValue将是name

angular rxjs
1个回答
1
投票

尝试

getItems(dataSourceUrl: string, bindKey: string, bindValue: string): Observable<SelectItem[]> {
     return this.httpClient.get<SelectItem[]>(dataSourceUrl)
           .pipe(map(x=> this.transformValue(bindKey,bindValue,x)));
}

transformValue(bindKey,bindValue,response):SelectItem[]{
    const newResponse = [];
    response.forEach(data => {
        newResponse.push({
            label: data[bindKey],
            value: data[bindValue]
        })
    })
    return newResponse;
}
© www.soinside.com 2019 - 2024. All rights reserved.