Search JSON using user date input from dropdown menus - javascript

I'm looking to be able to take a user date input from three different drop down menus (day, month, year) and use a JSON file that I created by exporting my database to a JSON file to pull back the data that matches the date inputted by the user.
Here's an example of a record in my JSON file:
"items": [
{"id":"1","artistName":"REDNEX","songTitle":"COTTON EYE JOE"," startDate":"1995-01-14"},
If the users input matches a date in the JSON array then I wish to display the artist name and song title. How would I go about doing this? I have never worked with JSON before now.
Thank you in advance for any help!

Let us assume obj as your JSON data.
var output = [];
var searchField = "startDate";
var searchVal = year+"-"+month+"-"+day;
for (var i=0 ; i < obj.list.length ; i++)
{
if (obj.list[i][searchField] == searchVal) {
output.push(obj.list[i]["artistName"] + "," + obj.list[i]["songTitle"]);
}
}

You can use the filter function
data = {"items": [
{"id":"1","artistName":"REDNEX","songTitle":"COTTON EYE JOE","startDate":"1995-01-14"},
]};
function getArtistByDate(date) {
items = data["items"];
return items.filter(
function(items){ return items["startDate"] == date }
);
}
console.log(getArtistByDate("1995-01-14"));
console.log(getArtistByDate("1995-01-15"));

You say "JSON", but your post includes what appears to be a raw javascript object. JSON data is simply a string, which can then converted to an object.
Addtionally, you want to use filter to select the artists of interest.
var userDate = "1995-01-14";
var itemString = '[{"id":"1","artistName":"REDNEX","songTitle":"COTTON EYE JOE", "startDate":"1995-01-14"}]'
var items = JSON.parse(itemString);
var filtered = items.filter(x => x.startDate === userDate);
for (var i = 0; i < filtered.length; ++i)
console.log(filtered[i].artistName + ": " + filtered[i].songTitle);

I would use takeWhile() from Lodash: https://lodash.com/docs/4.16.4#takeWhile. (Moreover, once you get started with Lodash you are going to find a wealth of utility functions that you cannot live without.)
var userInputDate;
var matchingItems = _.takeWhile(items, {'startDate': userInputDate});
// matchingItems is an array of all items with the same startDate

Related

How to find JSON data at specific index

I want to show only the country name like India,Srilanka etc.
{"result":1,"countries":[
{"country_id":"1","country_name":"Afghanistan"},
{"country_id":"2","country_name":"Albania"},
{"country_id":"3","country_name":"Algeria"},
{"country_id":"4","country_name":"American Samoa"},
{"country_id":"5","country_name":"Andorra"},
{"country_id":"6","country_name":"Angola"},
{"country_id":"7","country_name":"Anguilla"}
]
}
Below I have created JSON object same as yours:
var text = '{"result":1,"countries":[' +
'{"country_id":"1","country_name":"Afghanistan"},' +
'{"country_id":"2","country_name":"Albania"},' +
'{"country_id":"3","country_name":"Algeria"}'+
']}';
var obj = JSON.parse(text);
you can loop through JSON object and get each property value as below:
for(i = 0; i < obj.countries.length ; i++)
{
console.log(obj.countries[i].country_name);
}
Hope This Will Help!
why no iterate the objects and pull that data into a separate array? for example:
[[{"country_id":"1","country_name":"Afghanistan"},{"country_id":"2","country_name":"Albania"},{"country_id":"3","country_name":"Algeria"},{"country_id":"4","country_name":"American Samoa"},{"country_id":"5","country_name":"Andorra"},{"country_id":"6","country_name":"Angola"},{"country_id":"7","country_name":"Anguilla"}]]
.forEach(function(element) {
console.log(element.country_name);
});

Javascript in Zapier to return multiple values for posting to Airtable database

I am trying to write some javascript in Zapier which will read two dates and then return an array of all dates between those dates in such a way that they can then be used to create multiple dated records in Airtable (a database). From the Zapier help it says that if you return an array of objects then the following steps will be processed for each.
I have managed to get code which returns the data I wan but it can't be correct because if I try to create the database records only one is created - with all the dates in (so it will only work if output to a text field - not a date). Here's my code attempt:
var fromDate = new Date(inputData.from);
var toDate = new Date(inputData.to);
var output =[];
var i = 1;
do {
var useDate = new String(fromDate.toISOString())
output.push(useDate);
console.log(fromDate);
fromDate.setDate(fromDate.getDate() + 1);
i++
}
while (fromDate <= toDate);
console.log(output);
return{output};
The subsequent step does see the output variable - but it is treated as one value as I said above.
Does anyone have any ideas?
Thanks Juan
That sorted it - or at least it did after removing the return - here is the working code:
var fromDate = new Date(inputData.from);
var toDate = new Date(inputData.to);
var output =[];
var i = 1;
do {
var useDate = new String(fromDate.toISOString())
var dateObject = {};
dateObject.date = useDate;
output.push({dateObject});
fromDate.setDate(fromDate.getDate() + 1);
i++
}
while (fromDate <= toDate);
It looks like you're returning an object, not an array of objects:
return{output};
Also, your do/while statement is creating an array of strings, not objects. In your do block, instead of pushing the useDate string to the output array, you should construct a simple object and push that to the output array.
So instead of pushing '2016-09-28T00:00:00.000Z' each time the loop runs, you should push something like {date: '2016-09-28T00:00:00.000Z'}.
Your do block should look something like this:
do {
var useDate = new String(fromDate.toISOString());
var dateObject = {};
dateObject.date = useDate;
output.push(dateObject);
fromDate.setDate(fromDate.getDate() + 1);
i++
}
This way, output will be an array of objects:
[
{
"date": "2016-09-28T00:00:00.000Z"
},
{
"date": "2016-09-29T00:00:00.000Z"
},
{
"date": "2016-09-30T00:00:00.000Z"
}
]

restructure CSV data to create correct format in JSON

I'm working with some CSV data. Right now the CSV has a column called 'characteristic' which is one of three types, and a column called 'value', which contains the numerical value for the characteristic.
I'd like to change the structure of the data so that the columns are the characteristics themselves, and the values fall directly under those columns.
Here are screenshots of the tables, for clarity:
Currently:
What I'd like:
I changed things manually to give an example. The actual table I'll need to change is thousands of lines, so I'm hoping I can do this programmatically in some way.
The reason I need to restructure is that I need to transform the CSV to JSON, and the JSON needs to look like this:
[
{
"country":"afghanistan",
"iso3":"afg",
"first_indicator":3,
"second_indicator":5,
"third_indicator":3
},
{
"country":"united states",
"iso3":"usa",
"first_indicator":8,
"second_indicator":6,
"third_indicator":7
},
{
"country":"china",
"iso3":"chn",
"first_indicator":6,
"second_indicator":0.7,
"third_indicator":2
}
]
So - is there any way to take my CSV as it is now (first screenshot), and transform it to the JSON I want, without doing it all manually?
I've done a lot of searching, and I think maybe I just don't know what to search for. Ideally I would use javascript for this, but any suggestions welcome.
Thank you.
I made a JSFiddle for you, something like this should be what you want.
JavaScript
function Country(name, short){
this["country"] = name;
this["iso3"] = short;
}
function getCountryByName(name) {
for(var i = 0; i < countries.length; i++){
var country = countries[i];
if(country["country"] == name){
return country;
}
}
return null;
}
var csv = "country,shortname,characteristics,value\nafghanistan,afg,first_characteristic,3\nunited states,usa,first_characteristic,8\nchina,chn,first_characteristic,6\nafghanistan,afg,second_characteristic,5\nunited states,usa,second_characteristic,6\nchina,chn,second_characteristic,0.7\nafghanistan,afg,third_characteristic,3\nunited states,usa,third_characteristic,7\nchina,chn,third_characteristic,2"
var rows = csv.split("\n");
var countries = [];
if(rows.length > 0){
var header = rows[0];
var columns = header.split(",");
var countryIndex = columns.indexOf("country");
var shortnameIndex = columns.indexOf("shortname");
var characteristicsIndex = columns.indexOf("characteristics");
var valueIndex = columns.indexOf("value");
for(var i = 1; i < rows.length; i++) {
var row = rows[i];
var columns = row.split(",");
var name = columns[countryIndex];
var short = columns[shortnameIndex];
var characteristic = columns[characteristicsIndex];
var value = columns[valueIndex];
var country = getCountryByName(name);
if(!country){
country = new Country(name, short);
countries.push(country);
}
country[characteristic.replace("characteristic", "indicator")] = +value;
}
}
console.log(countries);
console.log(JSON.stringify(countries));
Output from the last line is this:
[{"country":"afghanistan","iso3":"afg","first_indicator":"3","second_indicator":"5","third_indicator":"3"},
{"country":"united states","iso3":"usa","first_indicator":"8","second_indicator":"6","third_indicator":"7"},
{"country":"china","iso3":"chn","first_indicator":"6","second_indicator":"0.7","third_indicator":"2"}]
My suggestion is to convert the CSV to JSON first. You can use an online tool.
When you have the JSON you can write a Javascript code to modify the JSON in the format you want.

Merging JSON data from multiple URL's and sorting them based on a key

I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw
Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.
Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)
$.getJSON(sourceUrl, function (data) {
//console.log(data);
//var you_data = JSON.stringify(data);
var videosCount = data.items.length;
console.log("The number of videos is: " + videosCount);
for ( i = 0 ; i < videosCount; i++) {
var title = data.items[i].snippet.title;
var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
$("#reply").append(" " + title + "<br><br><br>");
//console.log(title);
//console.log(url);
};
});
How do I get this done?
EDITED (my thoughts):
Something that I can think of is using nested objects. I can create a new object that two looks something like:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}
here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.
Solution:
I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:
function getAjaxData(sourceUrl) {
$.ajax({
async:false,
url:sourceUrl,
success: function(data) {
var videosCount = data.items.length;
for ( var i = 0 ; i < videosCount; i++) {
var tempobject = {};
tempobject.published = data.items[i].snippet.publishedAt;
tempobject.wholeItem = data.items[i];
wholearray.push(tempobject);
}
}
});
}
One solution is to create a new array of object literals, then sort the array based on the key:
var array = [];
$.getJSON(url, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
$.getJSON(otherUrl, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
Have a listener that waits for both AJAX calls to finish, then you can sort:
array.sort(function(a,b) { return a.published - b.published; });
This question gives more info on sorting
This may not be the most efficient way, but it's the first that comes to mind and will work swell!

Search JSON Array based on variable?

I've got a JSON Array that I need to search:
[
{
"Device_ID":"1",
"Image":"HTC-One-X.png",
"Manufacturer":"HTC",
"Model":"One X",
"Region":"GSM",
"Type":"Phone"
},
{
"Device_ID":"2",
"Image":"Motorola-Xoom.png",
"Manufacturer":"Motorola",
"Model":"Xoom",
"Region":"CDMA",
"Type":"Tablet"
},
{
"Device_ID":"8",
"Image":"null",
"Manufacturer":"Motorola",
"Model":"Xoom 2",
"Region":"CDMA",
"Type":"Tablet"
}
]
Using the keyword: $_GET['keyword']; I need to be able to do the following.
Search the combined value of Manufacturer and Model, ie. Motorola Xoom. Then, for whichever set of values matches this, output them to variables.
For example: If the Keyword was HTC, then it would search the array and output:
$DeviceID = 1 $Image = HTC-One-X.png $Manufacturer = HTC $Model = One
X $Region = GSM $Type = Type
However if the keyword was Motorola, then it would need to output all entries that include Motorola.
What im trying to do, is output a live view of all JSON Array entries, as the user types the keyword. However I want this to run on the users computer to reduce the load on the server.
Does anyone know the best way to go about this?
well if you have a selection box with the values for the manufacturer in the options section it's as easy as:
HTML:
<select id="selectionBox">
<option>...</option>
</select>
<div id="outPut">
output goes in here
</div>
Javascript:
var selectedValue = document.getElementById("selectionBox").value;
for(var i = 0; i < jsonObject.length; i++){
if(jsonObject[i].Manufacturer === selectedValue){
//considering your object is an array let's
for(var key in jsonObject[i]){
document.getElementById("outPut").innerHTML += jsonObject[i][key] + "</br>";
}
}
}
that'll pretty much print everything in the object onto the output div, the rest is up to your styling.
Here's a function for filtering the JSON. Displaying the data is up to you.
var devices = <your JSON array>;
function filter(keyword, data) {
var filteredArray = [], i, j;
for (i = 0, j = data.length; i < j; i++) {
if ((data[i].Manufacturer && data[i].Manufacturer.indexOf(keyword) !== -1) || (data[i].Model && data[i].Model.indexOf(keyword) !== -1)) {
filteredArray.push(data[i]);
}
}
return filteredArray;
}
// Example usage
var MotorolaDevices = filter('Motorola', devices);

Categories

Resources