ko.mapping is always an empty array - asp.net-mvc

Here is what I am returning from my controller:
var states = _dc.States.ToList();
var serializer = new JavaScriptSerializer();
ViewBag.StateList = serializer.Serialize(states);
My JS:
var stateList = #Html.Raw(ViewBag.StateList);
var stateListModel = ko.mapping.fromJS(stateList);
Is I do a console.log on stateListModel, it is always [], but stateList is a complete array with all the data.

The ko.mapping result is not an empty array, it is a function.
As nemesv's comment says, you have to do this:
var stateListModel = ko.mapping.fromJS(stateList);
var realArray = stateListModel();

Related

google script editor mailchimp - fetch segment subscriber

I'm currently trying to fetch mailchimp data for the total amount of subscribers within a predefined auto updating segment within our subscriber list into Google sheets using the script editor. However, I must confess I'm not very knowledgeable in this area and have tried various ways of customizing this code with no luck. I have looked at Mailchimps documentation regarding this but still cannot seem to get this work.
function chimpSubscribers() {
var API_KEY = ''; // MailChimp API Key
var LIST_ID = ''; // MailChimp List ID
var SEGMENT_ID =''; //Mailchimp Segment ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Subscribers");
var dc = API_KEY.split('-')[1];
var api = 'https://'+ dc +'.api.mailchimp.com/3.0';
var memberList = '/lists/'+LIST_ID
var memberSegment = '/segments/'+SEGMENT_ID
var apiCall = function(endpoint){
options = {"headers": {"authorization": 'apikey '+API_KEY}};
apiResponseMembers = UrlFetchApp.fetch(api+endpoint,options);
json = JSON.parse(apiResponseMembers);
return json
}
var members = apiCall ("memberList", "memberSegment");
if (members) {
var d = new Date();
var member_count = members.stats.member_count;
var unsubscribe_count = members.stats.unsubscribe_count;
var open_rate = members.stats.open_rate;
var click_rate = members.stats.click_rate;
var report = [d, member_count, unsubscribe_count, open_rate, click_rate,];
Logger.log(report);
// Clear MailChimp data in Spreadsheet
sheet.clear();
// Append MailChimp data to Spreadsheet
sheet.appendRow(["Date", "Total Subscribers", "Unsubscribe Count", "Open Rate", "Click Rate"]);
sheet.appendRow(report);
}
}
Figured it out - for anyone else that may need it the code is as follows:
function chimpSubscribers() {
var API_KEY = ''; // MailChimp API Key
var LIST_ID = ''; // MailChimp List ID
var SEGMENT_ID = ''; // Mailchimp Segment ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Subscribers");
var dc = API_KEY.split('-')[1];
var api = 'https://'+ dc +'.api.mailchimp.com/3.0';
var memberList = '/lists/'+LIST_ID +'/segments/'+ SEGMENT_ID
options = {"headers": {"authorization": 'apikey '+API_KEY}};
var apiCall = function(endpoint){
apiResponseMembers = UrlFetchApp.fetch(api+endpoint,options);
json = JSON.parse(apiResponseMembers);
return json
}
var members = apiCall(memberList);
if (members) {
var d = new Date();
var member_count = members.member_count;
var report = [d,member_count,];
Logger.log(report);
// Clear MailChimp data in Spreadsheet
sheet.clear();
// Append MailChimp data to Spreadsheet
sheet.appendRow(["Date", "Total Subscribers"]);
sheet.appendRow(report);
}
}

How do I create a dictionary from an array of objects in swift 2.1?

I have an array of type "drugList", and they are derived from a struct "DrugsLibrary":
struct DrugsLibrary {
var drugName = ""
var drugCategory = ""
var drugSubCategory = ""
}
var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["": [""," "]]
My data model is initialized using this function:
func createDrugsList() {
var drug1 = DrugsLibrary()
drug1.drugName = "drug1"
drug1.drugCategory = "Antibiotics"
drug1.drugSubCategory = "Penicillins"
self.drugList.append(drug1)
var drug2 = DrugsLibrary()
drug2.drugName = "drug2"
drug2.drugCategory = "Antibiotics"
drug2.drugSubCategory = "Penicillins"
self.drugList.append(drug2)
var drug3 = DrugsLibrary()
drug3.drugName = "drug2"
drug3.drugCategory = "Antibiotics"
drug3.drugSubCategory = "Macrolides"
self.drugList.append(drug3)
}
my problem is that i'm trying to create a dictionary from the drugList where the key is the drugSubCategory and the value is the drug name. The value should be an array if there are several drugs in this subcategory
for example, the dictionary should look something like this for this example:
dictionary = [
"Penicillins": ["drug1","drug2"]
"Macrolides": ["drug3"]
]
I tried this method:
for item in drugList {
dictionary["\(item.drugSubCategory)"] = ["\(item.drugName)"]
}
this gave a dictionary like this, and it couldn't append drug2 to "Penicllins":
dictionary = [
"Penicillins": ["drug1"]
"Macrolides": ["drug3"]
]
So I tried to append the items into the dictionary using this method but it didn't append anything because there were no common items with the key "" in the data model:
for item in drugList {
names1[item1.drugSubCategory]?.append(item1.drugName)
}
Anyone knows a way to append drug2 to the dictionary?
I would appreciate any help or suggestion in this matter.
You need to create a new array containing the contents of the previous array plus the new item or a new array plus the new item, and assign this to your dictionary:
for item in drugList {
dictionary[item.drugSubCategory] = dictionary[item.drugSubCategory] ?? [] + [item.drugName]
}
You can use .map and .filter and Set to your advantage here. First you want an array of dictionary keys, but no duplicates (so use a set)
let categories = Set(drugList.map{$0.drugSubCategory})
Then you want to iterate over the unique categories and find every drug in that category and extract its name:
for category in categories {
let filteredByCategory = drugList.filter {$0.drugSubCategory == category}
let extractDrugNames = filteredByCategory.map{$0.drugName}
dictionary[category] = extractDrugNames
}
Removing the for loop, if more Swifty-ness is desired, is left as an exercise to the reader ;).
I have two unrelated observations:
1) Not sure if you meant it as an example or not, but you've initialized dictionary with empty strings. You'll have to remove those in the future unless you want an empty strings entry. You're better off initializing an empty dictionary with the correct types:
var dictionary = [String:[String]]()
2) You don't need to use self. to access an instance variable. Your code is simple enough that it's very obvious what the scope of dictionary is (see this great writeup on self from a Programmers's stack exchange post.
Copy this in your Playground, might help you understand the Dictionaries better:
import UIKit
var str = "Hello, playground"
struct DrugsLibrary {
var drugName = ""
var drugCategory = ""
var drugSubCategory = ""
}
var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["":""]
func createDrugsList() {
var drug1 = DrugsLibrary()
drug1.drugName = "drug1"
drug1.drugCategory = "Antibiotics"
drug1.drugSubCategory = "Penicillins"
drugList.append(drug1)
var drug2 = DrugsLibrary()
drug2.drugName = "drug2"
drug2.drugCategory = "Antibiotics"
drug2.drugSubCategory = "Penicillins"
drugList.append(drug2)
var drug3 = DrugsLibrary()
drug3.drugName = "drug2"
drug3.drugCategory = "Antibiotics"
drug3.drugSubCategory = "Macrolides"
drugList.append(drug3)
}
createDrugsList()
print(drugList)
func addItemsToDict() {
for i in drugList {
dictionary["item \(i.drugSubCategory)"] = "\(i.drugName)"
}
}
addItemsToDict()
print(dictionary)

How can I sort an array of arrays (by variable name) using Swift?

(I'm not using Swift 2.0 at the time.)
I have multiple arrays inside a master array. I need them in alphabetical order by variable name, and I can't figure out how to sort anything other than Strings inside an array. These are my arrays:
var onDeck1 = [String]()
var onDeck2 = [String]()
var onDeck3 = [String]()
var onDeck4 = [String]()
My problem is that I keep running into something like this:
var masterArray = [onDeck1, onDeck4, onDeck3, onDeck2]
When I need this:
var masterArray = [onDeck1, onDeck2, onDeck3, onDeck4]
Anybody know what I need to do?
Try the following approach:
// var masterArray = [ onDeck1, onDeck4, onDeck3,onDeck2]
var masterArray = [ "Babisko", "Kapisko", "Hapisko"];
var sortedArray = masterArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

Swift: How to add dictionary arrays to an array?

Can I add dictionary arrays (is this the correct term for a dictionary key holding multiple values?) to an array?
var dictionary = [String: [String]]()
var array = [String]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
I tried this:
array.extend([dictionary["1"], dictionary["2"], dictionary["3"]])
but there was an error "Cannot invoke 'extend' with an argument list of type '([[(String)?])"..
How do I add dictionary["1"], ["2"] & ["3"] accordingly into the array?
Your array type declaration is not correct. Please try below one
var array: [[String:[String]] = []
In case you are not interested in the order you might try:
array.extend(flatMap(dictionary.values, {$0}))
If order is important you might build your optionalArrays first:
let optionalArrays = [dictionary["1"], dictionary["2"], dictionary["3"]]
array.extend(flatMap(optionalArrays, {$0 ?? []}))
i.e. your dictionary returns an optional array, this causes the error you reported.
Hope this helps
If you wanted an array of arrays of Strings, you need to change your array's type to be [[String]], as the other answers said.
But, when getting values out of your dictionary, you shouldn't force unwrap! It may work for this example, but in the future you'll likely get into trouble with:
'fatal error: unexpectedly found nil while unwrapping an Optional
value'
You should check to see if a value exists in the dictionary for that key, using optional binding for example:
if let value = dictionary["1"] {
array.append(value)
}
// ...
Or, you could get all the values from your dictionary into an array like so:
let array = Array(dictionary.values)
If you actually did want an array of Strings, you could use flatMap:
let array = flatMap(dictionary.values) { $0 }
Your array variable must be an Array of Array with String elements.
Also don't forget to unwrap the values of the dictionaries by adding !.
Try this:
var dictionary = [String: [String]]()
var array = [[String]]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
array.extend([dictionary["1"]!, dictionary["2"]!, dictionary["3"]!])
Dictionary values are returned as optionals (thus indicating if a value exists for a key) so use the '!' to unwrap the values of each dictionary array (i.e. [dictionary["1"]!)
And as suggested in other answers change your array type as it currently defined as arrays of string rather then an array of dictionaries.

How to get the first element value of the splitted array

How to get the first element value of the splitted array
var supplierpofileselection = $("[id$='_SelectedTabIdsHiddenField']").val();
var arr = supplierpofileselection.split(';');
var arrfirst = arr.first();
alert (arrfirst);
List is random.
You need to use index to access the element of array.
Change
var arrfirst = arr.first();
To
var arrfirst = arr[0];
Split method returns an array of substrings. So use indexes 0,1,2... to access value.
var supplierpofileselection = $("[id$='_SelectedTabIdsHiddenField']").val();
var arr = supplierpofileselection.split(';');
var arrfirst = arr[0];
alert (arrfirst);

Resources