[英]Extract specific keys from json using rxjs or native javascript
Assume that you have a json object as response.假设您有一个 json 对象作为响应。 eg例如
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'
}]
How to map the object in order to have only a result object like this:如何映射对象以便只有这样的结果对象:
[{
image: 'http://www.lorempixel.com/700/600/',
}, {
image: 'http://www.lorempixel.com/900/1200/',
}]
is there a clean way using rxjs operators?有没有使用 rxjs 运算符的干净方法? or simply js native?还是简单的js原生?
I tried it using :我尝试使用:
const source = from(items);
const result = source.pipe(
pluck('image')
);
result.subscribe(val => console.log('new values ', val));
But it's not working.但它不起作用。 Is there a cleaner way?有更干净的方法吗?
With vanilla JS just map
over the items and return objects with just that property:使用 vanilla 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);
Using Rxjs 6+使用 Rxjs 6+
It's works in rxjs like in Vanilla js.它在 rxjs 中就像在 Vanilla js 中一样工作。 here is an example from www.learnrxjs.io :这是来自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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.