Skip to content

Instantly share code, notes, and snippets.

@jimthedev
Created August 17, 2015 22:03
Show Gist options
  • Save jimthedev/d26b1264f4ea7a021a03 to your computer and use it in GitHub Desktop.
Save jimthedev/d26b1264f4ea7a021a03 to your computer and use it in GitHub Desktop.
Falcor object flatten to array for Angular 2
/**
* I am new to falcor and it is under development
* but I find that I keep needing to flatten
* integer keyed objects into arrays so that I can
* use them with Angular 2's NgFor directive.
*
* Perhaps I just need to write an angular pipe
* but I'm curious if there's a way to have falcor
* output arrays instead of keyed objects.
*
* I am using model.get so that I don't have to go
* to the server multiple times on first load. It
* works very well except for having to convert the
* keyed objects back into arrays.
*
* Any idea of better ways to accomplish this or if
* what I am doing is actually an antipattern?
*
* Thanks!
*
*/
Rx.Observable.fromPromise(model.get(
'showList[0..1].name',
'showList[0..1].show[0..5].performer.name',
'showList[0..1].show[0..5].performer.rating'
))
.pluck('json','showList') // Grab the path .json.showList
.map((x) => {
return flatten(x);
})
.subscribe((data) => {
// onNext value
this.data = data;
console.log(data);
}, (err) => {
// onError
this.errorMessage(err);
});
/**
* Takes an object like:
*
* { 0: 'a', 1: 'b', 2: 'c' }
*
* and outputs an array like:
*
* ['a', 'b', 'c']
*/
flatten(obj) {
return Object.keys(obj).reduce(function(previous, current) {
previous.push(obj[current]);
return previous;
}, []);
}
@atoy40
Copy link

atoy40 commented Jun 11, 2017

Just a detail, you don't need to use Observable.fromPromise() ... get() give you an Observable already.
Anthony.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment