![](/img/trans.png)
[英]Mapping data to Observable Array 1 based on field value from Observable Array 2
[英]Mapping an observable response as an array of custom interfaces in Angular
我有一个Observable keyValue(): Observable<{[id: number]: string;}>;
Observable 的论点是:
{
[id: number]: string;
}
正如你所看到的,第二个参数没有命名
现在我之前的 Observable 的一个结果是:
{1: 'Bad', 2: 'Good', 3: 'Worst', 4: 'Best', 5: 'Mean'}
我需要翻译成一个数组:
interface NumberKeyValue {
id: number;
value: string;
}
我正在尝试:
.keyValue()
.pipe(
map((kv) => {
console.log(kv);
const jsonObject = JSON.parse(JSON.stringify(kv));
console.log(jsonObject);
const nkvArray: NumberKeyValue[] = [];
for (const item of jsonObject) {
console.log(item);
const nkv: NumberKeyValue = {
id: 8, //How to catch the id number?
value: 'empty', //How to catch the string?
};
nkvArray.push(nkv);
}
return nkvArray;
})
)
.subscribe((response) => {
console.log(response);
});
在之前的代码之后,我得到了:
TypeError: jsonObject is not iterable
at MapSubscriber.project (template-sms.facade.ts:295)
at MapSubscriber._next (map.js:29)
at MapSubscriber.next (Subscriber.js:49)
at TapSubscriber._next (tap.js:46)
at TapSubscriber.next (Subscriber.js:49)
at SwitchMapSubscriber.notifyNext (switchMap.js:70)
at InnerSubscriber._next (InnerSubscriber.js:11)
at InnerSubscriber.next (Subscriber.js:49)
at MapSubscriber._next (map.js:35)
at MapSubscriber.next (Subscriber.js:49)
第一个也是主要的问题:如何转换为我的NumberKeyValue
接口的一个数组?
其次:这种类型表示是否有名称{[id: number]: string;}
?
对象类型确实不可迭代,但您可以使用Object.keys
获取一组键,然后您可以使用这些键以所需的形式投影数据:
.keyValue()
.pipe(
map((kv) => {
// use object destructuring to get a new reference instead of
// JSON.parse(JSON.stringify(something))
const jsonObject = { ...kv };
return Object.keys(jsonObject).map(key => ({ id: key, value: jsonObject[key] });
}),
).subscribe((response) => {
console.log(response);
});
根据Octavian
Answer,如您所见,需要使用+key
而不是key
; 和一个NumberKeyValue
接口数组。
.keyValue()
.pipe(
map((kv) => {
const jsonObject = { ...kv };
return Object
.keys(jsonObject)
.map((key) => {
const nkv: NumberKeyValue = { id: +key, value: jsonObject[+key] };
return nkv;
});
}),
)
.subscribe((response) => {
console.log(response);
});
以前,我以古老的形式思考。
.keyValue()
.pipe(
map((kv) => {
const numberKVArray: NumberKeyValue[] = [];
let response = JSON.stringify(kv);
response = response.replace(/[{}]/g, '');
const pairs = response.split('",');
for (const pair of pairs) {
const property = pair.split(':"');
property[0] = property[0].replace(/(^"|"$)/g, '');
property[1] = property[1].replace(/(^"|"$)/g, '');
const nkv: NumberKeyValue = {
id: +property[0],
value: property[1],
};
numberKVArray.push(nkv);
}
return numberKVArray;
}),
takeUntil(this.destroy$),
)
.subscribe((response) => {
console.log(response);
});
但是,第一个答案是最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.