假设您有一个json对象作为响应。例如
var items = [{
title: 'sample 1',
image: 'http://www.lorempixel.com/700/600/',
description: 'lorem ipsum'
}, {
title: 'sample 2',
image: 'http://www.lorempixel.com/900/1200/',
description: 'lorem ipsum'
}]
如何映射对象以仅具有这样的结果对象:
[{
image: 'http://www.lorempixel.com/700/600/',
}, {
image: 'http://www.lorempixel.com/900/1200/',
}]
是否有使用rxjs运算符的干净方法?或只是js本机?
我尝试使用:
const source = from(items);
const result = source.pipe(
pluck('image')
);
result.subscribe(val => console.log('new values ', val));
但是它不起作用。有没有更清洁的方法?
答案 0 :(得分:2)
使用香草JS,只需map
覆盖项目并返回具有该属性的对象:
var items = [{
title: 'sample 1',
image: 'http://www.lorempixel.com/700/600/',
description: 'lorem ipsum'
},{
title: 'sample 2',
image: 'http://www.lorempixel.com/900/1200/',
description: 'lorem ipsum'
}];
const out = items.map(({image}) => ({ image }));
console.log(out);
答案 1 :(得分:0)
使用Rxjs 6 +
它可以像Vanilla js一样在rxjs中工作。这是www.learnrxjs.io的示例:
// RxJS v6+
import { from } from 'rxjs';
import { map } from 'rxjs/operators';
//emit ({name: 'Joe', age: 30}, {name: 'Frank', age: 20},{name: 'Ryan', age: 50})
const source = from([
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 20 },
{ name: 'Ryan', age: 50 }
]);
//grab each persons name, could also use pluck for this scenario
const example = source.pipe(map(({ name }) => name));
//output: "Joe","Frank","Ryan"
const subscribe = example.subscribe(val => console.log(val));