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.
Related
brand new to Javascript.
I have figured out how to get data back from a Monday.com board, and it is returned as a JSON value like this:
{
"boards": [
{
"items": [
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "Cape Town, South Africa"
}
]
},
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "Paris, France"
}
]
},
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "New York, NY, USA"
}
]
}
]
}
]
}
There are 3 items here, but this amount can be anything.
I need to get the location text (e.g. "Cape Town, South Africa") and then I need to use this later in an API call to get the weather of this location.
I finally managed to display in the console the location, like this:
console.log(JSON.stringify(this.state.boardData.boards[0].items[0].column_values[0].text));
Obviously this then displays what I want, but only the value of the first item.
I need to do this dynamically to get all the locations, and I need to store this into variables, so that I can then make an API call to get the weather of each of the 3 (or more) locations.
I am totally lost and have been struggling for hours. Once I manage to do this, I still have no idea how I'll make the API call but one thing at a time :)
Another approach:
const rawData = {boards:[{items:[{column_values:[{id:"location",title:"Location",type:"location",text:"Cape Town, South Africa"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"Paris, France"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"New York, NY, USA"}]}]}]};
const locations = [];
for (const board of rawData.boards) {
for (const item of board.items) {
for (const value of item.column_values) {
locations.push(value.text);
}
}
}
console.log(locations);
You can extract the text with some amount of nested .map. Map boards => map items => map column_values. You will get an array of arrays of arrays. And then you can apply .flat() to unwrap them all. (.flat(Infinity); also can be used)
const apiData={boards:[{items:[{column_values:[{id:"location",title:"Location",type:"location",text:"Cape Town, South Africa"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"Paris, France"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"New York, NY, USA"}]}]}]};
const locations = apiData.boards
.map((board) => board.items.map((i) => i.column_values.map((cv) => cv.text)))
.flat(2);
console.log(locations);
So in javascript we have an array function map, using which we can iterate over array that can be used here. It would look something like this:
let arr = boards[0].items.map(element => element.column_values[0].text)
and this arr will contain the list of all the city names, which you can further use to send the data to api.
(Edit: considering column_values to be array with one element only and items can have multiple elements)
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 3 years ago.
I observed a very weird phenomena in javascript and I can't figure out why. Consider this example below
state = "West Bengal"
city = "Kolkata"
country = "India"
some_json = {country: {"city": city, "state": state, "col_val": {}}}
console.log(some_json)
When I do a console.log() of some_json variable, I get this below
{ country: { city: 'Kolkata', state: 'West Bengal', col_val: {} } }
As you can see it replaced every other variable's values with the one defined above except country. Why is that?
When I perform the same operation in Python, it works just fine.
state = "West Bengal"
city = "Kolkata"
country = "India"
some_json = {country: {"city": city, "state": state, "col_val": {}}}
print(some_json)
Here doing a print gives me the expected outcome
{'India': {'state': 'West Bengal', 'col_val': {}, 'city': 'Kolkata'}}
So why is it giving different outcome in javascript? How can I fix this since I need to work with this exact format?
When using a variable as key of an object in javascript use square bracket
let state = "West Bengal"
let city = "Kolkata"
let country = "India"
some_json = {
[country]: {
"city": city,
"state": state,
"col_val": {}
}
}
console.log(some_json)
You need to make country a dynamic property name with []:
var state = "West Bengal",
city = "Kolkata",
country = "India",
some_json = {
[country]: {
"city": city,
"state": state,
"col_val": {}
}
};
console.log(some_json);
Also for the record it's not a JSON object - JSON would be storing it as a string. It's a plain and simple JavaScript object.
When you do {country: {"city": city, "state": state, "col_val": {}}} here the country doesnot refer to country variable. If you your key to dynamic use Computed property names
Similarly when you want to access the property value using country variable don't use some_josn.country use Bracket Notation like this some_josn[country]
let state = "West Bengal"
let city = "Kolkata"
let country = "India"
some_json = {[country]: {"city": city, "state": state, "col_val": {}}}
console.log(some_json)
console.log(some_json[country]) //accesing "Inida" from "some_json"
use it like this, and it will work
state = "West Bengal"
city = "Kolkata"
country = "India"
some_json = {}
some_json[country] = {"city": city, "state": state, "col_val": {}}
console.log(some_json)
As you said it's working in python, Python will consider it as dictionary not as JSON object.
In JavaScript, by default it replaces only value part of JSON with variable. It won't consider key to be replaced with variable value.
To force JavaScript to consider key and replace it with variable value, you have to tell to JavaScript explicitly by using []. Try below code:
state = "West Bengal"
city = "Kolkata"
country = "India"
some_json = {[country]: {"city": city, "state": state, "col_val": {}}}
console.log(some_json)
I have a geoJson file structured this way:
"type":"Feature",
"id":"AFG",
"properties":{
"name":"Afghanistan"
},
"geometry":{
"type":"Polygon",
"coordinates":[
[
[
61.210817,
35.650072
It's the whole world and I need to grab all the country names and have them as a list the following in order to be able to use them for the autocomplete:
var availableTags = [
"Afghanistan",
"Angola",
"Albania",
"United Arab Emirates",
"Angola",
"Albania",
"United Arab Emirates",
....
How would I grab the country names as a list based on the geoJson object?
Here it is :
geoJson = //your geoJson Obj;
var countries = [];
for(var k in geoJson.features) {
countries.push(geoJson.features[k].properties.name);
}
console.log(countries);
Use countries as array for your autoComplete.
var a = <YOUR GEOJSON>;
var countries = a.features.map(function (item) {
return item.properties.name;
})
You can use Array#map()
data.features.map(o=>o.properties.name)
here is your updated JsFiddle
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.
I am working with JSON data in a JavaScript object like this:
var data = [
{ "City" : "New York", "State" : "New York" },
{ "City" : "Fargo", "State" : "North Dakota" },
{ "City" : "Los Angeles", "State" : "California" }
];
And I want to remove state data so it ends up like this:
var data = [
{ "City" : "New York"},
{ "City" : "Fargo"},
{ "City" : "Los Angeles"}
];
Currently I'm looping through and removing it but is there a way to remove the city from the object without having to loop through?
I found the "delete" operator ("The delete operator removes a property from an object.") but it seems to only work if there is just one item with that property, not globally as in the example object.
delete object["State"] //doesn't work
Edit: My bad. I copy/pasted and edited incorrectly. I have changed the original post to use correct format as supplied in Mr. Polywhirl's answer.
Edit: I ended up using the map method as suggested by mccainz. Using map allows for pulling all of a certain key/value pair (like city) from one array into another. You can also pull multiple like
newData = data
.map(function(v){
return {City:v.City, State:v.State};
});
It will work for my purposes and is better since I'm keeping the minority of the key/value pairs. However, it doesn't appear that there are any solutions for performing the task in the original question. For example, if you had 100 different key/value pairs per array item, you'd have to add 99 to a new array instead of being able to just remove one from the existing.
You should convert your data to an array of objects and simply operate on the array. The example below uses array.map to return an array with the State properties absent. However, there are numerous ways to skin this cat.
(edited to demonstrate a filtering preprocess before the map)
var data=[];
data.push({"City":"New York","State":"New York"});
data.push({"City":"Fargo","State":"North Dakota"});
data.push({"City":"Los Angeles","State":"California"});
var newData;
newData = data
.filter(function(v){
return v.State !=='California';
})
.map(function(v){
return {City:v.City};
});
Array.prototype.filter
Array.prototype.map
As others have indicated, you can't have duplicate properties in your JSON object. Your data is meant to be in an Array, not in one monster object.
If you don't want to modify the original object, you can combine map and reduce to create filtered objects.
var data = [
{ "City" : "New York", "State" : "New York" },
{ "City" : "Fargo", "State" : "North Dakota" },
{ "City" : "Los Angeles", "State" : "California" }
];
var filterKeys = function(data, keysToFilter) {
return data.map(function(item) {
return Object.keys(item).reduce(function(result, key) {
if (keysToFilter.indexOf(key) === -1) result[key] = item[key];
return result;
}, {});
});
}
document.body.innerHTML = JSON.stringify(filterKeys(data, ['State']), null, ' ');
body {
font-family: monospace;
white-space: pre;
}
Result
[
{ "City": "New York" },
{ "City": "Fargo" },
{ "City": "Los Angeles" }
]
you cant initiate an object with two identical keys.for example
var obj={city:"NEW YORK",city:"NEW JERSEY"}
city property will hold NEW JERSEY.because it's overwritten.
JSON.stringify(obj); // {"city":"NEW JERSEY"}
if you initiate an object with your json.your obj1 will hold only one city and state property.
JSON.stringify(obj1); //{"City":"Fargo","State":"North Dakota"}