TaffyDB alphabetical order - javascript

I am using TaffyDB (JavaScript library) and was able to successfully store my records into a database but I am having some trouble outputting the results in the correct format.
results().select("Name","Topic","Difficulty"))
This code would output my columns in alphabetical order. It would output as (Difficulty, Name, Topic) but I need to output it as ("Name, Topic, Difficulty"). I've tried looking at the documentation but I wasn't able to make a working solution.

results().select("Name","Topic","Difficulty"))
should be
results().select("Name","Topic","Difficulty")
notice the extra ")" at the end.
I have tried using your code and it DOESNT return in an alphabetical order.
go to http://www.javascriptoo.com/taffydb and change the code inside the script to :
var people= TAFFY();
people.insert({"fname":"Bruce","lname":"Wayne", "id":1});
people.insert({"fname":"Peter","lname":"Parker", "id":2});
people.insert({"fname":"Clark","lname":"Kent", "id":3});
write("people().select('fname','lname', 'id')");
function write(func){
var ret = eval(func);
var output = (typeof ret === 'object') ? JSON.stringify(ret) : ret;
document.getElementById('results').innerHTML+= '<li>' + func + '<br />=><b>'+output+'</b>';
}

Related

How to get "numFound" using JSON query for Solr?

I am simply trying to obtain the "numFound" figure from a Solr query in a piece of javascript.
At present the code I have outputs the number of responses, limited to X rows I specify, as well as X number of items.
What I want instead is the "numFound" value in the response, and to store it as a var in my javascript.
In the example below it would be 394.
{
"responseHeader":{
"zkConnected":true,
"status":0,
"QTime":31,
"params":{
"q":"names:\"Leo Varadkar\" AND region:\"ROI\""}},
"response":{"numFound":394,"start":0,"maxScore":11.911881,"docs":[
I don't want any info from the fields of a specific entry or anything like that. In my python code I can obtain such a figure by something like "solr.search(query).hits". However I have been unable to find an equivalent from poking around with this. I have tried to guess something like "data.response.hits" and the like but to no avail. I am really in the dark here!
I have been unable to find clear documentation on how to do this, or an example of someone doing the same thing, despite it seeming like quite an important aspect of the whole point of queries in Solr. Top 50 results are no use to me. I am dealing with tens of thousands of items. My confusion might suggest I am failing to understand some key aspect of the whole thing...but I don't think so?
All I want is that figure. Surely somebody knows how to get it? I bet it's very simple.
My javascript below:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function on_data(data) {
$('#results').empty();
var docs = data.response.docs;
$.each(docs, function(i, item) {
$('#results').prepend($('<div>' + item.name + '</div>'));
});
var hits = 'Found ' + data.response. + ' hits'
$('#hits').prepend('<div>' + hits + '</div>');
var total = 'Found ' + docs.length + ' results';
$('#results').prepend('<div>' + total + '</div>');
}
function on_search() {
var query = $('#query').val();
if (query.length == 0) {
return;
}
var url='http://localhost:8983/solr/articles/select?q=text:'+query+'&version=2.2&start=0&rows=10000&indent=on&wt=json&callback=?&json.wrf=on_data';
var urlB='http://localhost:8983/solr/articles/select?q=text:'+query+'&version=2.2&start=0&rows=50&indent=on&wt=json&callback=?&json.wrf=on_data';
$.getJSON(urlB);
}
function on_ready() {
$('#search').click(on_search);
/* Hook enter to search */
$('body').keypress(function(e) {
if (e.keyCode == '13') {
on_search();
}
});
}
$(document).ready(on_ready);
The structure is {"response":{"numFound":394 ... }}, which is loaded into your data variable.
var hits = 'Found ' + data.response.numFound + ' hits'
.. should give you the number you're looking for. The hits name is just given by various libraries (probably pysolr in your case) to the same value.
You can also use console.log(data) to see the parsed data structure in your developer tools' console window.

convert or parse string to JSON object

There was an interview question(Javascript) which my friend and me unable to solve it for a long time, so thought of asking here,
Question:
String:
2014<18.3,11.4,12.1,19.5,1000&&11.2,34.5,67.1,18,20000>name=sample,position=engineer,company=abc
and the end reult should be a JSON Objwct with following format. Can anyone please help to solve this issue.
Output:
{[
{"Proposal":"2014"},
{"values":"[18.3,11.4,12.1,19.5],[11.2,34.5,67.1,18]"},
{"Items":"[1000,20000]"},
{"name":"sample"},
{"position":"engineer"},
{"company":"abc"},
]}
Expecting a solution and explanation please.
Thanks,
Basky
Here is your solution.
Input string should have all the parameter, if any of the parameter is missing below code will break.
Logic is dynamic to support any number of numeric values where as last digit will consider as Items.
Logic also support the n number of key/value pair in the input string.
Check below code in console.
var JsonOutput = [];
var sRawInput = "2014<18.3,11.4,12.1,19.5,1000&&11.2,34.5,67.1,18,20000>name=sample,position=engineer,company=abc";
JsonOutput.push({ "Proposal" : sRawInput.split("<")[0] });
var oValues = sRawInput.split("<")[1].split(">")[0].split("&&");
var oActualValues = [];
var oActualItems = [];
$(oValues).each(function(Ind, Val){
oActualValues.push(Val.split(",").slice(0, Val.split(",").length - 1).join());
oActualItems.push(Val.split(",")[Val.split(",").length - 1]);
});
JsonOutput.push({ "Values" : oActualValues });
JsonOutput.push({ "Items" : oActualItems });
var OtherValues = sRawInput.split(">")[1].split(",");
$(OtherValues).each(function(Ind, Val){
JsonOutput.push(JSON.parse("{\"" + Val.split("=")[0] + "\":\"" + Val.split("=")[1] + "\"}"));
});
console.log(JsonOutput);
console.log(JSON.stringify(JsonOutput));
Note:
Values is incorrect as it should contain 2 arrays and not a single array.
Items is incorrect as it should contain numbers and not a string.
Also the outside wrapper should be an obj {}

covert large array of objects into smaller array objects using javascript

I have an list of values like this from a sql database.
UserName Email ComputerName DateIssued
jjsmith jjsmith#example.com JTComputer 9/14/2013
ltjoseph ltjoseph#example.com LTComputer1 10/21/2013
KTsmith KevinTem#example.com KTComputer1 01/25/2012
ltjoseph ltjoseph#example.com LTComputer2 01/11/2013
KTsmith KevinTem#example.com KTComputer2 01/25/2012
I transform my list into an array of objects.
var user_array = [
{"username":"jjsmith", "email":"jjsmith#example.com", "computerName":"JTComputer", "dateissued":"10/21/2013"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer1", "dateissued":"10/21/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer1", "dateissued":"01/25/2012"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer2", "dateissued":"01/11/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer2", "dateissued":"01/25/2012"}]
A function has been created by someone else that sends emails to users, it only accepts two parameters which are strings.
So I don't want to send more than 1 email per user. So I am trying to figure out how to combine the items together so that my an example set of strings look like this.
var str1 = "ltjoseph#example.com";
var str2 = "ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013";
and then fire the other user function to send emails for each of the items in the list.
function sendEmails(str1, str2);
If anyone has any ideas how i can do this. Please advise..
var by_user = {};
for (var i = 0; i < user_array.length; i++) {
if (by_user[user_array[i].username]) {
// Found user, add another computer
by_user[user_array[i].username].str2 += ', ' + user_array[i].computerName + '-' + user_array[i].dateissued;
} else {
// First entry for user, create initial object
by_user[user_array[i].username] = {
str1: user_array[i].email,
str2: user_array[i].username + ', ' + user_array[i].computerName + '-' + user_array[i].dateissued
};
}
}
Now you have the by_user object, which has a single sub-object for each user, whose str1 and str2 properties are the variables you want.
by_user['ltjoseph'].str1 => ltjoseph#example.com
by_user['ltjoseph'].str2 => ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013
something like this:
var str1=array[0].email
var str2=array[0].username+", "+array[0].computerName+array[0].dateissued
or use a loop and iterate through the array
I strongly recommend bringing in a library like lodash for this sort of thing and using uniq (sample here: http://jsfiddle.net/MwYtU/):
var uniqs = lodash(user_array).pluck('email').uniq().value();
If you're doing javascript and aren't acquainted with lodash or underscore, go do that because it'll save you a lot of time. Using tried and true code is a good idea. Added bonus: if you want to see how the pros are doing something like uniq you can just look at the source code.

how to parse csv by csv-jQuery and generate report?

imagine that you have csv data like this that I can read them from a textarea on my web page:
A,10,USA
B,5,UK
A,2,USA
I am trying to use cs-jQuery to parse and process this data to get the following report:
A has ran 12 miles with average of 6.
B has ran 5 miles with average of 5.
The code that I have written looks like this:
<script>
$(document).ready(function() {
$('#calculate').click(function() {
$('#report').empty();
var data = $('#input').val();
var values = $.csv.toObjects(data);
$('#report').append(values);
alert(values);
});
});
</script>
but all I am getting is [object Object] [object Object]...
any suggestion on what I should do? any way to do this with jQuery functionality?
this function $.csv.toObjects() return array of objects
Useful for parsing multi-line CSV data into an array of objects
representing data in the form {header:value}. Unless overridden, the
first line of data is assumed to contain the headers.
You don't have header so you should use $.csv.toArrays() instead and iterate over that array:
$.each($.csv.toArrays(data), function(_, row) {
$('#report').append('<div>' + row[0] + ' has ran ' + row[1] + ' miles</div>');
});
if you want to use toObjects you need to put header
person,miles,country
A,10,USA
B,5,UK
A,2,USA
and access it using row.person row.miles and row.country

How to encode cookie with javascript/jquery?

I am working on an online shop together with my friend. He set a cookie for me with PHP with the amount of added products to the Cart. The cookie is called "cart", and the variable with the amount of the products is called "items".
And I have to read the cookie and get the value of "cart" back with javascript and print it in the HTML document, but I have no Idea how to use it, can you please help me? I have never worked with cookies or JSON before, but I think it should be done with JSON, can you please explain it to me how it works?
when I do : console.log(document.cookie);
I receive something like this: cart=%7B%22items%22%3A%7B%228%22%3A1%7D%7D;
And I have no idea how to encode it.
Thank you
That is the URL encoded equivalent of {"items":{"8":1}} which is the JSON string you want.
All you have to do is decode it and parse the JSON:
var cart = JSON.parse(decodeURIComponent(document.cookie.cart));
Then logging cart should give you an object with an 'items' property that you can access as needed.
EDIT:
As an example, here's a way to iterate through the items and determine the total number of items and the total of all their quantities.
var items_total = 0,
quantity_total = 0;
for (var prop in cart.items) {
items_total += 1;
quantity_total += cart.items[prop];
}
console.log("Total Items: " + items_total);
console.log("Total Quantities: " + quantity_total);
Looks like you just need to decode it, then you will want to parse/eval it to get a workable object:
var obj, decoded = decodeURIComponent(document.cookie.cart);
if(window.JSON && JSON.parse){
obj = JSON.parse(decoded);
} else {
eval('obj = ' + decoded);
}
// obj == {"items":{"8":1}};

Categories

Resources