I have the following data which is being parsed and then I am looping through to attempt to get each state ID and name.
{
"billing": {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria",
"WA": "Western Australia"
},
"shipping": {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria",
"WA": "Western Australia"
}
}
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON( data );
billingData = data.billing;
$(billingData).each( function( key, value ) {
console.log( key + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am expecting the console to loop through each state ID and the label, but I get they key as 0 and the value as an object, I have also tried looping through the outputted object (contained in value from the original .each).
I have also tried looping through billingData[0].
You need to use jQuery.each() instead of .each() to do this work.
The .each() loop through jquery elements but jQuery.each() loop through array or object.
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON(data);
billingData = data.billing;
$.each(billingData, function(key, value) {
console.log(key +": "+ value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
billingData is not an array. It's an object. jQuery each will let you iterate through an object as though it were an array, or you could just use object methods:
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON(data);
billingData = data.billing;
Object.keys(billingData).forEach(function(key) {
console.log(key + ": " + billingData[key])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There are two types of each:
$.each(array, function( key, value ) {
});
$('.element').each(function () {
});
Related
I am new to JavaScript so I am struggling to even know where to start. Please can someone help me.
I have this array of ingredients:
const ingris = [
"1 cup heavy cream",
"8 ounces paprika",
"1 Chopped Tomato",
"1/2 Cup yogurt",
"1 packet pasta ",
"1/2 teaspoon freshly ground black pepper, divided",
]
I am trying to take out for example the 1 cup or 1/2 teaspoon (first 2 words of the array) and add it to a new array of objects like below:
const ShoppingList = [
{
val: "heavy cream",
amount: "1 cup",
},
{
val: "Tomato",
amount: "1 Chopped ",
},
{
val: "yogurt",
amount: "1/2 Cup",
},
];
Probably I would try to use .map() first iterate through the array of strings and convert it into an new array of objects. On each iteration you can .split() the string by spaces and most probably the first 2 elements of the array can be the amount property and the rest is the value.
See from the documentations:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.
Try as the following:
const ingris = [
"1 cup heavy cream",
"8 ounces paprika",
"1 Chopped Tomato",
"1/2 Cup yogurt",
"1 packet pasta",
"1/2 teaspoon freshly ground black pepper, divided",
];
const result = ingris.map(e => {
const split = e.split(' ');
const amount = `${split[0]} ${split[1]}`;
return { val: e.replace(`${amount} `, ''), amount };
});
console.log(result);
Probably you need to add fallback once you have different format of input strings, like checking if you have at least 3 words in that string.
Using Array#map to map the given array to a new one. Split the string to an arry at the spaces. return a new object with the first 2 array-elements as val and the others as amount. For gettuing the last elements use Array#slice and Array#join with a space as glue to connect them to a string.
const ingris = [
"1 cup heavy cream",
"8 ounces paprika",
"1 Chopped Tomato",
"1/2 Cup yogurt",
"1 packet pasta ",
"1/2 teaspoon freshly ground black pepper, divided",
];
let result = ingris.map(str => {
let arr = str.split(' ');
return {val: arr[0] + ' ' + arr[1], amount: arr.slice(2).join(' ')};
});
console.log(result);
There are multiple approach but using Array.prototype.map to loop over the array, String.prototype.split to turn each string into a array inside the loop, Array.prototype.slice() to get a slice from the array will help you create what you need. But keep in mind that it currently always get the first 2 words and the words after that. So your ingredients have to be the same way every time
const ingris = [
"1 cup heavy cream",
"8 ounces paprika",
"1 Chopped Tomato",
"1/2 Cup yogurt",
"1 packet pasta ",
"1/2 teaspoon freshly ground black pepper, divided",
];
const shoppingList = ingris.map(ingredient => {
const splitIngredient = ingredient.split(' ');
const amount = splitIngredient.slice(0, 2).join(' ');
const val = splitIngredient.slice(2, splitIngredient.length).join(' ');
return { val, amount };
});
console.log(shoppingList);
I am currently implementing google places autocomplete and the module I am using in React Native gives me the address as a whole string and not in address components. However, I need to have the postal code and city separate. The example response always look like this:
address: 'Calle Gran Vía, 8, 28013 Madrid, Spain
From this string I would need to have an object that looks like this:
{
city: 'Madrid',
postal_code: 28013,
}
How could I achieve this?
It's not the most "clean" or "smooth" answer, but it's something:
var response = "address: 'Calle Gran Vía, 8, 28013 Madrid, Spain";
var subStr = response.split(",")[2];
var obj = {
city: subStr.split(" ")[2],
postal_code: subStr.split(" ")[1]
};
console.log(obj);
For the city I think the best way is to use an array of cities and search it in the string
var str = "Calle Gran Vía, 8, 28013 Madrid, Spain";
var cities = ["Paris", "Berlin", "Madrid"];
var city = cities.filter(function(item) {
if (str.search(item) != -1)
return item;
})[0] || null;
For the postal code you should use a regex depending on the country (a good list of regex by country)
Probably split the string by ',' with array methods, take the third element of the array and split that by ' ', then you have your data points.
If you can always count on it being in that same format, you can do the following.
var splitAdress = address.split(",");
//This will give you ["Calle Gran Vía", " 8", " 28013 Madrid", " Spain"]
splitAdress = splitAdress[2].split(" ");
//This will give you ["", "28013", "Madrid"]
You'll first split the string into an array based on the comma and then follow it up by splitting on the space. The extra element in the second array is due to the space. This is an example of what #CBroe pointed out in the comments.
list=adress.split(",")[2].split()
list[0] gives you the postal code
list[1] gives you the city name
It depend on if there is always a comma in the "Calle Gran Vía, 8", if not you can use instead list=adress.split(",")[-2].split()
You might want to try this.
var address="Calle Gran Vía, 8, 28013 Madrid, Spain";
var splits = address.split(',')[2].trim().split(' ');
var newAdd = {
city : splits[1],
postal_code : splits[0]
}
console.log(newAdd);
I have a requirement where in I get JSON data from backend and I have to show that in textarea.currently, the data comes but its not formatted and validated.Now
1)How can I beautify JSON in the textarea ?
2)How can I validate it before saving ?
I have searched for all javascript/jquery plugins but I am not getting what I want.I want something like jslint
Thanks in advance
Use JSON.stringify(object, 0, 4) with space parameter for a formatted JSON string.
var object = [{ "stop_id": 70021, "stop_name": "CALTRAIN - 22ND ST STATION", "stop_lat": 37.757692, "stop_lon": -122.392318, "zone_id": 3329 }, { "stop_id": 70022, "stop_name": "CALTRAIN - 22ND ST STATION", "stop_lat": 37.757692, "stop_lon": -122.392318, "zone_id": 3329 }, { "stop_id": 70151, "stop_name": "CALTRAIN - ATHERTON STATION", "stop_lat": 37.464458, "stop_lon": -122.198152, "zone_id": 3331 }];
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can use the following to check that a string is a valid representation of a JSON object:
function parseJson(str) {
try {
return JSON.parse(str);
}
catch (err) {
return false;
}
}
Usage:
var parsed = parseJson(someInput);
if (parsed === false) {
// Invalid json
}
If you also need to validate the object using some custom logic (e.g. "I need your object to have attributes X and Y"), take a look at JsonSchema.
"[{rest_id:"2", cate_id:"4", rest_name:"Samraat Curry Hut", adress:"6275 Jarvis Ave, Newark, CA 94560", city:"Newark", state:"New Jersey", country:"US", email_id:"", rest_url:"Samraat-Curry-Hut", phone_no:"(510) 745-7000", rest_image:"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]"
top array my result but my required bottom array add double quote key
rest_id to "rest_id" all key add double quote("")
my required array
This Angular JS
first JSON is my input and output second array
[{"rest_id":"2", "cate_id":"4", "rest_name":"Samraat Curry Hut", "adress":"6275 Jarvis Ave, Newark, CA 94560", "city":"Newark", "state":"New Jersey", "country":"US", "email_id":"", "rest_url":"Samraat-Curry-Hut", "phone_no":"(510) 745-7000", "rest_image":"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]
Take a look at JSON.parse (if you want to use it as a JSON object)
var foo = JSON.parse("[{rest_id:"2", ...}]");
You can do one thing use regular expressing in that case:-
var a= JSON.stringify([{"rest_id":"2", "cate_id":"4", "rest_name":"Samraat Curry Hut", "adress":"6275 Jarvis Ave, Newark, CA 94560", "city":"Newark", "state":"New Jersey", "country":"US", "email_id":"", "rest_url":"Samraat-Curry-Hut", "phone_no":"(510) 745-7000", "rest_image":"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]);
a=a.replace(/"(\w+)"\s*:/g, '$1:');
Fiddle
I have an alert dependent on an array containing around 38 of the 50 United States, It works fine (thanks to help from you wonderful people) but now I'm concerned users may input variations of the format I am using currently which is two uppercase letters (i.e. WA, OR, GA etc). What if they are to input lowercase (i.e. wa, or, ga) or maybe a combination of uppercase and lowercase (i.e. Wa, Or, Ga) or with symbols (i.e. WA - Washington, OR - Oregon, GA - Georgia). Wondering if there is a more accurate way of doing this that will catch all variations.
The alert I'm referring to is the last one, at the bottom pointing toward #address_province.
Please note I am very new at using both Javascript and jQuery so as much detail as you can offer is appreciated.
Thank you very much in advance.
<script>
// Hides shipping info fieldset if ship to billing is checked
$(function () {
$("#ship_to_billing").change(function () {
if ($(this).is(":checked")) $("#shipping_info").hide();
else $("#shipping_info").show();
});
});
// Validates address fields are filled out unless ship to billing is checked...
function validateShipping() {
if (!$("#ship_to_billing").is(":checked")) {
var inputs = $("#shipping_info input");
var ready = true;
inputs.each(function () {
if ($(this).val() == '') {
ready = false;
return false;
}
});
if (!ready) {
alert("Please tell us where to send this. Either choose ship to Billing Address or fill out both the Recipient Name as well as Shipping Address fields. Thanks!");
return false;
}
}
// Makes sure age verification is checked
if (!$('#age_verification').is(':checked')) {
alert("Please verify you are 21 years of age or older.");
return false;
}
// Confirms province is allowed for wine shipping
var states = ["AK", "AZ", "CA", "CO", "CT", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "LA", "ME", "MD", "MI", "MN", "MO", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OR", "SC", "TN", "TX", "VT", "VA", "WA", "WV", "WI", "WY"];
if ($.inArray($("#address_province").val(), states) <0) {
alert("Shipping gifts containing alcohol to this state is prohibited by law. Please choose another item.");
return false;
}
return true;
}
</script>
The case concerns can be handled using the String.toUpperCase function. You'd simply take the value they've entered, convert it to upper case, and then compare it against the values in your array. So, regardless of whether they enter WA, Wa, wa, or wA, you'll be using WA for the comparison.
The user entering the value in some other format, such as WA - Washington can be handled in a few ways. One solution would be to simply take the first two characters (so you'd get WA), but that doesn't work if they enter the state name on its own; it would work for Washington, but not for Georgia.
I'd be inclined to enforce a limit of 2 characters on the input box using the maxlength attribute (maxlength="2"). That should be supported by all browsers and makes it clear that you're expecting a state code rather than a state name.
One final option is, if that validation is always applicable, to use a <select> element that only includes valid states. That would remove the need for client-side validation altogether (though you'd still need to do server-side validation).
http://jsbin.com/uQEJIkU/1/edit
$(document).ready(function() {
var state = "Wisconsin";
var result = state.slice(0,2).toUpperCase()
alert(result)
});
All merit goes to #Anthony_Grist as he had the first answer in the comment.