How to iterate over an array and constructing an object from the results of a PostgreSQL query - arrays

Here's my problem:
var ps = ["P1", "P2"];
var hs = ["H1", "H2"];
var jOut = {};
hs.forEach(async (h) => {
var t = `t_${h}`;
var query = {
text: `SELECT pName, pPrice FROM ${t} WHERE pName = ANY($1)`,
values: [ps],
rowMode: "array"
};
var qres = await client.query(query);
jOut[t] = qres.rows;
});
console.log(jOut);
I want the output to look something like this:
{
t_H1: [ [pName: "P1", pPrice: 0.5], [pName: "P2", pPrice: 1.2] ],
t_H2: [ [pName: "P1", pPrice: 0.6], [pName: "P2", pPrice: 1.0] ]
}
But instead my output looks like this:
{}

forEach loop doesn't wait for promises until they are resolved, that's why
console.log(jOut);
is immediately executed before all/any of your promises are resolved.
Instead use for..of loop
for(const h of hs) {
var t = `t_${h}`;
var query = {
text: `SELECT pName, pPrice FROM ${t} WHERE pName = ANY($1)`,
values: [ps],
rowMode: "array"
};
var qres = await client.query(query);
jOut[t] = qres.rows;
}
console.log(jOut);

Related

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

Get count of values in json data and create variable based on those for c3 table

I am trying to create a dynamic donut chart as I don’t know how many variables will be coming in but the dataset will be in the 10,000's with between 1 and 20 variables.
I have got my data into an array as below.
How do I create a var for each unique element in the array and its count i.e var 1 = [sys1, 94] or similer so they can be used in the columns and colours config
Original data
res.data[{system:'sys1'},
{system:'sys1'},
{system:'sys2'},
{system:'sys1'},
{system:'sys3'},
{system:'sys3'}]
Getting keys
var array_elements = []
angular.forEach(res.data, function(value, key){
if (array_elements.indexOf(value.system) === -1){
array_elements.push(value.system)
}
})
array_elements = ["sys1", "sys2", "sys3"];
config
var donutData = {
type : 'donut',
colors: {
Cats: $.pfPaletteColors.blue,
Hamsters: $.pfPaletteColors.green,
Fish: $.pfPaletteColors.orange,
Dogs: $.pfPaletteColors.red
},
columns: [
['Dogs', 2],
['Cats', 2],
['Fish', 3],
['Hamsters', 1]
],
You can do something like this:
var data = [{
system: 'sys1'
}, {
system: 'sys1'
}, {
system: 'sys2'
}, {
system: 'sys1'
}, {
system: 'sys3'
}, {
system: 'sys3'
}];
var tmp = {};
data.forEach(function(x) {
tmp[x.system] = (tmp[x.system] || 0) + 1;
});
var keys = Object.keys(graphData);
var finalData = [];
for(var i = 0; i < keys.length; i++) {
var x = [];
x.push(keys[i]);
x.push(graphData[keys[i]]);
finalData.push(x);
}
console.log(finalData);
Fiddle example

storing multiple objects using HTML5 indexDB

I have JSON object in the below format,
$scope.indexData = {
"custid": "1",
"addresses": [
{
"addressType": "P",
"address1": ""
},
{
"addressType": "M"
}
],
"personalDetails": {
"title": "",
"name": ""
}
}
I want to store the object using HTML5 indexDB. how do i store the object?
I tried in the following way, but no luck.
var db;
var request = window.indexedDB.open("newDatabase", 1);
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("customers");
for (var i in $scope.indexData) {
objectStore.add($scope.indexData[i]);
}
}
I am getting the following error saying: Uncaught DataError: Failed to execute 'add' on 'IDBObjectStore': The object store uses out-of-line keys and has no key generator and the key parameter was not provided.
You are specifying a keypath which instruct the store to use in-line keys. your code maybe like this:
var db;
var request = window.indexedDB.open("newDatabase", 1);
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("customers",{keyPath: "isbn"});
for (var i in $scope.indexData) {
objectStore.add({i:$scope.indexData[i], isbn:i});
}
}

how to fill <array> struct by another struct

My app in Xcode with swift language programming :
I have a struct like:
struct PageFilter {
var key: Int?
var title: NSString?
}
And then I have the values in:
filters are coming from API and i am saving them to extractedFilter
if let filters = filters {
for filter in filters {
var extractedFilter = PageFilter()
extractedFilter.key = filter["key"].integerValue
extractedFilter.title = filter["title"].stringValue
}
}
I have an array of page filter like :
lazy var availableFilters = Array<PageFilter>()
I want to fill the availableFilters with ExtractedFilter.
******* *i fixed the issue by a loop like this code :
var strFilter : String = ""
for var i = 0; i < self.newFilterList.availableGuildFilters.count; i++ {
let guildFilter = self.newFilterList.availableGuildFilters[i]
if guildFilter.selected {
strFilter += "\(guildFilter.key),"
}
}
thanks to all*
The following Swift 1.2 playground code would do it - I have put in a function to simulate the call to the API
//: Playground - noun: a place where people can play
import Cocoa
struct PageFilter {
var key: Int?
var title: NSString?
}
// this would be replaced by whatever way you get your filters from the API
func getFiltersFromApi() -> [PageFilter]? {
// return nil // uncomment this line to demo the API returning nothing
return [PageFilter(key: 1, title: "one"),
PageFilter(key: 2, title: "two"),
PageFilter(key: 3, title: "three"),
PageFilter(key: nil, title: nil)
]
}
let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil
let extractedFilters: [PageFilter]
if let filters = filters {
extractedFilters = filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
extractedFilters = []
}
for filter in extractedFilters {
println("key: \(filter.key), title: \(filter.title)")
}
Alternatively you could have your lazy var like this
var availableFilters: [PageFilter] = {
let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil
if let filters = filters {
return filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
return []
}
}()
The code is similar to Leonardo's answer, the main difference being the use of the map function instead of for ... in ...
Try like this:
struct PageFilter {
var key = Int()
var title = String()
}
var filters:[PageFilter]? = []
filters = [PageFilter(key: 1, title: "one"), PageFilter(key: 2, title: "two"), PageFilter(key: 3, title: "three")]
var extractedFilter = Array<PageFilter>()
if let filters = filters {
for filter in filters {
extractedFilter.append(PageFilter(key: filter.key, title: filter.title))
}
}
println(extractedFilter[1].key) // "2"
println(extractedFilter[1].title) // "two"
I fixed the issue by a loop like this:
var strFilter : String = ""
for var i = 0; i < self.newFilterList.availableGuildFilters.count; i++ {
let guildFilter = self.newFilterList.availableGuildFilters[i]
if guildFilter.selected {
strFilter += "\(guildFilter.key),"
}
}

How do I get my Filters from Filtersfeature

I am using FiltersFeature:
this.features = {
ftype: 'filters',
encode: false,
local: true
};
I would like to access my current filters on my table. Ie. not the filter configuration object, but what the changes user has done to the table (I want to save this in the database).
There is a filters object on grid, but that just gives me the filter configuration from all the columns.
handler: function (btn) {
var grid = btn.up('grid');
grid.filters
}
I need the actual values. I'm looking for something like this:
var v = {
filter: {
column: 'name',
value: 'bob'
},
filter: {
column: 'date',
value1: '11.11.11',
value2: '12.12.12'
}
}
Anyone know where i can get this info?
The answer I found out was to use this method :)
myTableGrid.filters.getFilterData()
I get something like this :
v = [{
"field": "myColumn1",
"data": {
"type": "string",
"value": "anna"}
}, {
"field": "myColumn2_fixedvalue",
"data": {
"type": "list",
"value": [60]}
}]
Filter does not contain any values.
You should parse actual values from the grid.
var columnTitle = [];
var fieldName = [];
var data = [];
var visibleColumns = grid.query('gridcolumn:not([hidden])');
visibleColumns.forEach(function(c) {
columnTitle.push(c.text);
fieldName.push(c.dataIndex);
});
for (rowIndex = 0; rowIndex < grid.store.getCount(); rowIndex++) {
var row = grid.getView().getRow(rowIndex);
var fieldValues = Ext.fly(row).query('div.x-grid-cell-inner');
var map = {}
for (colIndex = 0; colIndex < fieldName.length; colIndex++) {
map[fieldName[colIndex]] = fieldValues[colIndex].textContent;
}
data.push(map);
}
As a result, you will get an array of objects, something like
[{"user.login":"iivanov","email":"ivanov#mail.com"},{"user.login":"ppetrov","email":"petrov#mail.com"},{"user.login":"plosev","email":"elk#gmail.com"}]

Resources