Reputation: 547
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.
Upvotes: 2
Views: 4925
Reputation: 1073
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)
})
args
filteringSome useful links:
Upvotes: 1
Reputation: 36703
You 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);
Upvotes: 5
Reputation: 29335
observables are for manipulations of streams of data over time, so they are array like but they are not arrays. If this data is coming 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)})));
Upvotes: 0