I have the following script from the e164.js library.
Normally from chrome debugger, I'll use e164.lookup('44123486789); and I'll get the value: Object {Country: "United Kingdom", Code: "UK"}
How can I read a phone number from a html div and display the returned result in another html div?
for example say
<div id="phone">44123486789</div>
and write the result to:
<div id="country"></div>
Thanks guys.
Here is the script:
(function() {
var lookup, prefixes = {
"1201": [ "US", "United States" ],
"1202": [ "US", "United States" ],
"1203": [ "US", "United States" ],
"1204": [ "CA", "Canada" ],
"44": [ "GB", "United Kingdom" ],
};
lookup = function(phone) {
if (phone.length) {
var prefix, c = phone.length;
for (c; c >= 0; c=c-1) {
prefix = phone.substring(0, c);
if (prefixes[prefix]) {
return { country: prefixes[prefix][1], code: prefixes[prefix][0] };
}
}
}
};
if (typeof exports !== "undefined"){
exports.lookup = lookup;
}
if (typeof window !== "undefined"){
window.e164 = { lookup : lookup};
}
})();
var phone = document.getElementById('phone').innerHTML;
var country = lookup(phone).country;
document.getElementById('country').innerHTML = country;
It'll need to go inside that anonymous function you have there (since the function lookup is defined inside the scope of that outer function). And that outer anonymous function will need to run after those two divs (and the phone number) are present -- you should probably wait for the load event on window.
Related
I'm trying to create an advance search function to use on a multi-dimensional array of product objects. On the form, the user will have the option of narrowing down product results based on data in several different attributes (e.g. "'price' < 20 && 'country' == 'France'", "region == 'New York' && 'vintage' == '2016' && 'qty > 20"). The data, within variable data is formatted as follows:
0:
name: "Kedem Cream Red Concord"
appellation: "New York"
country: "United States"
price: "10.99"
primarygrape: "Concord"
qty: "1"
region: "New York"
regprice: "10.99"
sku: "230"
vintage: "NV"
1:
name: "Kendall Jackson Vintner's Chardonnay"
appellation: ""
country: "United States"
price: "14.99"
primarygrape: "Chardonnay"
qty: "35"
region: "California"
regprice: "18.99"
sku: "345"
vintage: "2016"
... continuing on over 10,000 product records
I figured I could create a string based on the user form input fairly easily that sums up what they're searching for. However, I need a safe way to evaluate that string within my function that returns the filtered results in resultsArray
I was able to get it to work with the eval() function, but I know that's not safe or efficient. I also tried fooling around with putting the conditions into an array and trying to incorporate that into the for loop, but I couldn't figure out how to make it work. The tricky part is, the conditions could be any number of things involving the following product attributes: appellation, country, price, primarygrape, qty, region, vintage. And different attributes use different operators (e.g. country, region, and others use '==' while qty and price use '>' or '<').
This code works, but uses the taboo eval() function:
var conditional = "data[i].price < 20 && data[i].country == 'France' && data[i].vintage == '2016'";
var resultArray = [];
console.log(data.length);
for (var i = 0; i < data.length; i++)
{
if (eval(conditional))
{
resultArray.push(data[i]);
}
}
}
This doesn't work, as it results in a Uncaught ReferenceError: data is not defined error:
var conditional = "return data[i].price < 20 && data[i].country == 'France' && data[i].vintage == '2016'";
var resultArray = [];
console.log(data.length);
for (var i = 0; i < data.length; i++)
{
if (new Function(conditional)())
{
resultArray.push(data[i]);
}
}
}
Any idea how to dynamically create that if conditional statement so that it recognizes the data variable? Or, is there a better solution?
Javascript Arrays have a function called filter which can be used to do things like you want to achieve.
For example you have an array with numbers:
var arr = [1,3,6,2,6]
And your plan is to filter all even numbers.You can use array.filter().
you need to pass an anonymous function into it. This function gets called once every entry in which you have access to the current element.
You need to return a boolean in this function - true means
that the element will be in the new, filtered array
Now the completed example to filter all even numbers:
arr.filter(function(element) {return element%2 == 0})
I hope that's enough for you to continue. :-) In the next snippet I made a small example with your data array
var your_data_array = [
{
name: "Kendall Jackson Vintner's Chardonnay",
appellation: "",
country: "United States",
price: "14.99",
primarygrape: "Chardonnay",
qty: "35",
region: "California",
regprice: "18.99",
sku: "345",
vintage: "2016" },
{
name: "Kendall Jackson Vintner's Chardonnay",
appellation: "",
country: "United States",
price: "14.99",
primarygrape: "Chardonnay",
qty: "35",
region: "California",
regprice: "18.99",
sku: "345",
vintage: "2016" },
{
name: "Kendall Jackson Vintner's Chardonnay",
appellation: "",
country: "United States",
price: "14.99",
primarygrape: "Chardonnay",
qty: "35",
region: "California",
regprice: "18.99",
sku: "345",
vintage: "2016" }
]
var filtered_array = your_data_array.filter(function(dataElement) {
return dataElement.country == "United States";
})
console.log(filtered_array)
If you are getting the conditions based on user input, you can format it how you like, it doesn't need to be a string. I would recommend an array that looks something like this:
var conditions = [
{
property: 'price',
comparator: '<',
value: 20
},
{
property: 'country',
comparator: '=',
value: 'France'
}
];
You could then use the filter method to generate your results array:
var resultArray = data.filter(function(item) {
for (var i = 0; i < conditions.length; i++) {
if (conditions[i].comparator === '=' &&
item[conditions[i].property] !== conditions[i].value) {
return false;
}
if (conditions[i].comparator === '>' &&
item[conditions[i].property] <= conditions[i].value) {
return false;
}
if (conditions[i].comparator === '<' &&
item[conditions[i].property] >= conditions[i].value) {
return false;
}
}
})
I want to iterate through this object by creating a function country(state,foods)
if the state and foods exists in the object,it should return me the state name and foods array of that state.First i tried iterating only state by passing argument state in the function using for in still i didn't get the state name and i don't know what should i do to get foods array.
var india = [
{
"state": "karnataka",
"capital": "Bengaluru",
"foods": ["Mysore masala", "Uthhappa", "Bisi Bele Bhaat"]
},
{
"state": "Maharashtra",
"capital": "Mumbai",
"foods": ["vada pav", "puranpoli", "Missal pav"]
},
{
"state": "Tamil nadu",
"capital": "Chennai",
"foods": ["Medu vada", "aapam", "idli sambhar"]
},
{
"state": "Rajasthan",
"capital": "Jaipur",
"foods": ["Ras malai", "Kadka", "Gujia"]
}
];
This is a poor data structure for your use case, so if you expect to need to search this data often, you might consider having state names as properties on an object for O(1) lookup rather than O(n) approach of iterating this array. That being said, this existing structure can be searched in this case using Array.find().
var result = india.find( item => (item.state === this) , searchState);
console.log(result.foods);
for (var i in india)
{
alert(india[i].state);
// do something else with india[i]
}
Or since india is an array:
for (var i = 0; i < india.length; ++i)
{
// same thing
}
When searching if a specific number or string exists in an array you can use Array.indexOf(), example:
if (india[i].foods.indexOf('Kadka') >= 0)
{
alert(india[i].state + " has food Kadka");
}
A function StateHasFood(state, food) could be something like that:
function StateHasFood(state, food)
{
for (var i in india)
if (india[i].state == state)
return india[i].foods.indexOf(food) >= 0;
return false;
}
Of course you can also return the object relative to the state containing its properties, including it's name and full list of foods like you seem to want:
function StateHasFood(state, food)
{
for (var i in india)
if (india[i].state == state)
if (india[i].foods.indexOf(food) >= 0)
return india[i];
return false;
}
Since you just told me to write a function to check if state and capital are present, and that is true then return the capital. I have wrote this for you. Hope it helps :)
var india = [
{
"state": "karnataka",
"capital": "Bengaluru",
"foods": ["Mysore masala", "Uthhappa", "Bisi Bele Bhaat"]
},
{
"state": "Maharashtra",
"capital": "Mumbai",
"foods": ["vada pav", "puranpoli", "Missal pav"]
},
{
"state": "Tamil nadu",
"capital": "Chennai",
"foods": ["Medu vada", "aapam", "idli sambhar"]
},
{
"state": "Rajasthan",
"capital": "Jaipur",
"foods": ["Ras malai", "Kadka", "Gujia"]
}
];
function country(someState , someCapital){
for (var i in india)
{
if(india[i].state === someState && india[i].capital === someCapital){
return india[i].capital;
}
}
}
document.write(country("Tamil nadu", "Chennai"));
From what you've added in the comments, it seems what you really want is a function getPropForState(state, prop) that will return the value of the specified property associated with the specified state. That is, getPropForState("Rajasthan", "foods") would return an array of foods, and getPropForState("Rajasthan", "capital") would return "Jaipur".
Assuming that is the case, perhaps something like the following:
// same array as in question, but with line breaks removed
// so that it doesn't clutter up my answer
var india = [{"state":"karnataka","capital":"Bengaluru","foods":["Mysore masala","Uthhappa","Bisi Bele Bhaat"]},{"state":"Maharashtra","capital":"Mumbai","foods":["vada pav","puranpoli","Missal pav"]},{"state":"Tamil nadu","capital":"Chennai","foods":["Medu vada","aapam","idli sambhar"]},{"state":"Rajasthan","capital":"Jaipur","foods":["Ras malai","Kadka","Gujia"]}];
function getPropForState(state, prop) {
var item = india.find(v => v.state === state);
if (item)
return item[prop];
}
console.log(getPropForState("Rajasthan", "foods")); // returns ["Ras malai","Kadka","Gujia"]
console.log(getPropForState("Rajasthan", "capital")); // returns "Jaipur"
console.log(getPropForState("Maharashtra", "capital")); // returns "Mumbai"
console.log(getPropForState("Maharashtra", "missing")); // returns undefined
console.log(getPropForState("Queensland", "foods")); // returns undefined
Note that if either the state or the specified other property do not exist then the function will return undefined.
Try forEach() method to iterate and Object.keys to get the key:value pairs. Don't completely understand OP's objective so I'll add objArrKey(). This function takes the array and a specific key and return all values associated with said key.
SNIPPET
var India = [{
"state": "karnataka",
"capital": "Bengaluru",
"foods": [
"Mysoremasala",
"Uthhappa",
"BisiBeleBhaat"
]
}, {
"state": "Maharashtra",
"capital": "Mumbai",
"foods": [
"vadapav",
"puranpoli",
"Missalpav"
]
}, {
"state": "Tamilnadu",
"capital": "Chennai",
"foods": [
"Meduvada",
"aapam",
"idlisambhar"
]
}, {
"state": "Rajasthan",
"capital": "Jaipur",
"foods": [
"Rasmalai",
"Kadka",
"Gujia"
]
}]
India.forEach(function(item) {
Object.keys(item).forEach(function(key) {
console.log("key:" + key + " value:" + item[key]);
});
});
function objArrKey(arr, key) {
return arr.map(function(item) {
return item[key] || null;
});
}
console.log(objArrKey(India, ['state']));
console.log(objArrKey(India, ['capital']));
console.log(objArrKey(India, ['foods']));
Using vanilla JavaScript (supported by the latest version of Chrome, don't worry about IE) and/or lodash/underscore but no jQuery how can I take this array:
[
{
"id": 1,
"places": {
"city": "boston"
}
},
{
"id": 2,
"places": {
"city": "new york"
}
}
]
...and remove the entire object that has a city of "boston":
[
{
"id": 2,
"places": {
"city": "new york"
}
}
]
Please keep in mind this array could have dozens of entries. Thank you!
http://plnkr.co/edit/JW3zd6A7OcmihM4CTh1D?p=preview
One of the ways you can do this is by using filter. For example:
var dataWithoutBoston = data.filter(function (el) {
return el.places.city !== "boston";
});
And to make it reusable, you can have a function like this:
function removeFromCity(data, name) {
var result = data.filter(function (el) {
return el.places.city !== name;
});
return result;
};
I am attempting to export data in my Google Sheets to a BI dashboard (Geckoboards). For the particular widget I'm using, the JSON is required in the format like so:
{
"points": {
"point": [
{
"city": {
"city_name": "London",
"country_code": "GB"
},
"size": 10
},
{
"city": {
"city_name": "San Francisco",
"country_code": "US",
"region_code": "CA"
I don't need to worry about the size property right now, however. Currently I've modified a Google Script from an example for this purpose, but it is not working and I don't think I have the loop correctly set up to produce JSON in the proper format:
var apiKey = "#########################omitted";
function geckoDocsJSONmap()
{
var jsonSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("JSON Demo Data");
var widgetKey;
widgetKey = ##########omitted";
var aCity = jsonSheet.getRange("A2:A5").getValues();
var aCountry = jsonSheet.getRange("B2:B5").getValues();
var aRegion = jsonSheet.getRange("C2:C5").getValues();
gdMap_(widgetKey, aCity, aCountry, aRegion);
function pushWidgetUpdate_(widgetKey, payload, options)
{
var payload = JSON.stringify(payload);
var options =
{
"method" : "post",
"payload" : payload
};
var jsonResponse = UrlFetchApp.fetch("https://push.geckoboard.com/v1/send/" + widgetKey, options);
Logger.log(JSON.parse(jsonResponse.getContentText()));
return(true);
}
function gdMap_(widgetKey, aCity, aCountry, aRegion)
{
for (var i = 0; i < aCity[0].length; i++)
{
var payload =
{
api_key:apiKey,
data:
{
points:
{
point : [
{
city: {
city_name: aCity,
country_code: aCountry,
region_code: aRegion }
}
]
}
}
}
}
return(pushWidgetUpdate_(widgetKey, payload));
}
}
I can't seem to provide a picture of the Google Sheet I am using because I don't have enough reputation, but I've published it here:
Google Sheet
Any help with this is much appreciated. I'm very much a novice still in my JavaScript ability, and even more so with Google Scripts.
First see how JSON should look like
[
{"ShortCode":"US","Name":"United States"},
{"ShortCode":"CA","Name":"Canada"},
{"ShortCode":"AG","Name":"Antigua and/or Barbuda"}
]
Code:
var countries = [];
map = {};
// This is going to make an HTTP post request to the controller
return $.post('/Client/CountryLookup', { query: query }, function (data) {
// Loop through and push to the array
$.each(data, function (i, country) {
map[country.Name] = country;
countries.push(country.Name);
});
$post() will return the above json & i need to parse the json in each loop
but i do not understand what will be store in map object this line map[country.Name] = country;
Suppose country name is "united state" so actually store will be map['united state']=country what does it mean?
Even in the save code map{} access later like
var selectedShortCode = map[item].ShortCode;
How map can have a property like ShortCode ??
So please discuss this type of coding technique in detail and help me to understand the above code with few more example. thanks
your map is an object literal defined also known as hash or dictionary or relational array in other languages what basically relates a key(Strin) with a value(anything) in this case relates country names with the actual country object thats why
the map structure after your map[country.Name] = country operations would be
{
"United States":{"ShortCode":"US","Name":"United States"},
"Canada":{"ShortCode":"CA","Name":"Canada"},
"Antigua and/or Barbuda":{"ShortCode":"AG","Name":"Antigua and/or Barbuda"}
}
then when you do
map["United States"]
you get
{"ShortCode":"US","Name":"United States"}
Your data after the $.post call would be:
data =
[
{ ShortCode: "US", Name: "United States" },
{ ShortCode: "CA", Name: "Canada" },
{ ShortCode: "AG", Name: "Antigua and/or Barbuda" }
];
Take a look at the jQuery's .each function documentation.
It basically can be rewritten as follows:
for(var i in data)
{
var country = data[i];
map[country.Name] = country;
countries.push(country.Name);
}
So you end up with:
map =
{
"United States": { ShortCode: "US", Name: "United States" },
"Canada": { ShortCode: "CA", Name: "Canada" },
"Antigua and/or Barbuda": { ShortCode: "AG", Name: "Antigua and/or Barbuda" }
};
countries = [ "United States", "Canada", "Antigua and/or Barbuda" ];
So your code parses json, and outputs all the countries that exist (countries) and all the data associated with them (map), in two different objects. countries can be used to easily itterate through the map, but there's no real need for it.
EDIT:
var country = data[0];
// country = { ShortCode: "US", Name: "United States" };
map[country.Name] = country;
// map["United States"] = { ShortCode: "US", Name: "United States" };
So you can later take map["United States"], it will return you an object { ShortCode: "US", Name: "United States" }, then you can simply access it's property ShortCode if you'd like to.
Mind that all variables in JavaScript are passed by reference, and that myObject["someProperty"] is exactly the same as myObject.someProperty.