Created
August 17, 2015 22:03
-
-
Save jimthedev/d26b1264f4ea7a021a03 to your computer and use it in GitHub Desktop.
Falcor object flatten to array for Angular 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a detail, you don't need to use Observable.fromPromise() ... get() give you an Observable already.
Anthony.