I have a bit of code that draws from a Taffy db, to create an object that I then iterate through. In previous versions, the order of the elements in the object were consistent in their order (although I realize this is not guaranteed in js), so I was accessing them through this[0]
, this[1]
, etc. In the new version (apparently due to a Taffy bug, https://github.com/typicaljoe/taffydb/issues/109), this behaviour is not reliable, so I would like to know if there is a more robust way to structure the information and retrieve it. A minimal example:
var stuffWeCite = TAFFY([{
"first": 1,
"second": 2,
"third": 3,
"fourth": 4
}]);
var filterVar = {"first":1};
var someVar = stuffWeCite()
.filter(filterVar)
.select("first", "second", "third", "fourth");
console.log('someVar: ' + someVar);
Previously, the result would appear 1, 2, 3, 4, but the behaviour has changed.
If I were entering the elements of the query into an object one-by-one, I would assign them properties ("first", "second", etc.) and then call those later, but the way they are selected seems to preclude this. Is there a way I can assign properties to the values when creating the object from a db query?
I don't know taffy, but for such kind of problem, i use an array helper, as you mentioned the order of the object keys are not reliable in javascript. You can declare an array which keeps the keys of the object in the order that you would like to use, then iterate it to get the values in the order from the object:
var stuffWeCite = TAFFY([{
"second": 2,
"first": 1,
"fourth": 4
"third": 3,
}]);
var array = ['first', 'second', 'third', 'fourth'];
array.forEach(function(item) {
console.log(stuffWeCite[item]);
});
or with for loop:
var stuffWeCite = TAFFY([{
"second": 2,
"first": 1,
"fourth": 4
"third": 3,
}]);
var array = ['first', 'second', 'third', 'fourth'];
for (var i = 0, l = array.length; i<l; i++) {
console.log(stuffWeCite[array[i]]);
}
For iterating through set of objects received from db, considering no. of fields you want to use small, so not necessary to iterate array:
var friendsInSeattle = friends({city:"Seattle, WA"});
var fieldsInOrder = ['id', 'gender', 'first', 'last'];
friendsInSeattle.forEach(function(friend) {
console.log({
fieldsInOrder[0]: friend(fieldsInOrder[0]),
fieldsInOrder[1]: friend(fieldsInOrder[1]),
fieldsInOrder[2]: friend(fieldsInOrder[2]),
fieldsInOrder[3]: friend(fieldsInOrder[3])
});
});
Of course you can construct the object while you iterate the fields array, if you have more fields, or fields may change in the future. Hope this helps.