Let say I have a array like this:
[
{
name:"1",
args: [1,2,3,4,5]
},
{
name:"2",
args: [2,3,4,5,6]
}
]
What I want to do, is to remove all "args" that have a value < 4, to have the following result:
[
{
name:"1",
args: [4,5]
},
{
name:"2",
args: [4,5,6]
}
]
How can I do that using Observables (Rxjs). I tried with mergeMap, but it does seems to do what I want.
Let say I have a array like this:
[
{
name:"1",
args: [1,2,3,4,5]
},
{
name:"2",
args: [2,3,4,5,6]
}
]
What I want to do, is to remove all "args" that have a value < 4, to have the following result:
[
{
name:"1",
args: [4,5]
},
{
name:"2",
args: [4,5,6]
}
]
How can I do that using Observables (Rxjs). I tried with mergeMap, but it does seems to do what I want.
Share Improve this question edited Oct 26, 2017 at 9:34 artur grzesiak 20.4k5 gold badges48 silver badges56 bronze badges asked Oct 25, 2017 at 17:28 tlevequetleveque 5473 gold badges9 silver badges18 bronze badges3 Answers
Reset to default 5You can do this pretty easily using plain JS.
var data = [
{
name:"1",
args: [1,2,3,4,5]
},
{
name:"2",
args: [2,3,4,5,6]
}
];
var parsedData = data.map(function(el){
el.args = el.args.filter(function(x){ return x >= 4; });
return el;
});
console.log(parsedData);
If you want RxJS-way solution, it might look something like this:
ES6 syntax:
const arr = [
{
name:"1",
args: [1,2,3,4,5]
},
{
name:"2",
args: [2,3,4,5,6]
}
]
Rx.Observable
.from(arr) // 1
.map(item => { // 2
return {
...item,
args: item.args.filter(arg => arg >= 4) // 3
}
})
.reduce((acc, value) => [...acc, value], []) // 4
.subscribe(result => {
console.log(result) // 5
})
ES5 syntax:
var arr = [
{
name:"1",
args: [1,2,3,4,5]
},
{
name:"2",
args: [2,3,4,5,6]
}
]
Rx.Observable
.from(arr)
.map(function(item) {
return {
name: item.name,
args: item.args.filter(function(arg) {
return arg >= 4
})
}
})
.reduce(function(acc, value) {
return [].concat(acc, value)
}, [])
.subscribe(function(result) {
console.log(result)
})
- Create Observable sequence from array
- Modify each streamed item in array corresponding to your needs
- Actual
args
filtering - Reduce all streamed results into one array (you can remove this line if you want then process each item of array one-by-one, not the whole array)
- Do something with result
Some useful links:
- Observable.from() method
- map() operator
- reduce() operator
observables are for manipulations of streams of data over time, so they are array like but they are not arrays. If this data is ing through an observable, you should just use map and then use normal array operators inside the observable map, because you're just manipulating a single data point in the stream:
source.map(data => data.map(d => Object.assign(d, {args:d.args.filter(v => v >= 4)})));