So, I have this object containing country names as keys and the values are arrays with some cities. I want to get all the cities in one array, without the countries. Here's how I go about it and can't understand why it isn't working:
var cities = {
"United Kingdom": ['london'],
"Spain": ['ibiza', 'malaga'],
"USA": ['hollywood']
}
var allCities = [];
for (c in cities) {
allCities.concat(cities[c]);
}
console.log(allCities); //gives empty array
If I replace allCities.concat(cities[c]) with console.log(cities[c]) I get all the arrays like this:
['london']
['ibiza', 'malaga']
['hollywood']
So that's where my frustration comes from. Any idea why this isn't working?
As per documentation of Array.prototype.concat:
Returns a new array comprised of this array joined with other array(s)
and/or value(s).
Which means it does not modify the object it is applied to.
Change to:
allCities = allCities.concat(cities[c]);
Related
I have the mapping of abbreviation and full name as follow:
object = {"TSLA":"TESLA INC.","GOOG":"GOOGLE INC.","APPL":"APPLE INC.","AMZN":"AMAZON CORPORATION", "MSFT":"MICROSOFT CORPORATION"}
as an output of function i get the following array:
array = ["AMZN","APPL"]
I want to display the values of the associated keys as follows:
output_array = ["AMAZON CORPORATION", "APPLE INC."]
Note that, the actual object has more key: value pairs
Using IndexOf() I can replace one value. However, I believe there must be a way of mapping the array elements to replace the values at once.
Since I am new to JS, I would appreciate any suggestion.
array.map(abbr => object[abbr]) does the job; it iterates over the array rather than the object, which is more efficient as the object already is a lookup table with the right keys - you are right, there is no need to use indexOf which uses a linear search.
I want to create object similar to this using loop, where I have separate array of country codes and another array of latitude and longitudes
is there any way to achieve this in typescript,
var latlong={
'us': {'latitude':39.528019315435685, 'longitude':-99.1444409552122},
'fr': {'latitude':46.62065825554313, 'longitude':2.4521888685061306}
}
Assuming that your arrays have corresponding index, then you can use this sample code,
let country = ['us','fr'];
let lat = ['39.528019315435685','46.62065825554313'];
let long = ['-99.1444409552122','2.4521888685061306'];
let latlong = {};
country.forEach((code,index)=>{
latlong[code] = {};
latlong[code]['latitude'] = lat[index];
latlong[code]['longitude'] = long[index];
})
Assuming that both arrays are correctly mapped through their indices, you could try :
coordinatesArray.forEach((coordinate, index)=>{
latlong[countryArray[index]] = coordinate;
});
where coordinatesArray contains an array of latitude and longitude objects and countryArray contains the country string.
Here's small example of way to create desired object.
CodeSandbox-project
Basically you iterate through other array and with index reference to your other array. with obj[key] you can create object with variables as keys.
And just to open a bit discussion about achieving this in TypeScript. TypeScript basically only extends existing EcmaScript-syntax with types so this would work in vanillaJS or in TypeScript as expected. Benefit you get in TypeScript is if you would have typed your variables.
eg.
const country: string[] = ['fr','en']
So now your IDE can show you that you expect country-variable only to contain strings.
Struggling with some javascript array manipulation/updating. Hope someone could help.
I have an array:
array('saved_designs'=array());
Javascript JSON version:
{"saved_design":{}}
I will be adding a label, and associated array data:
array("saved_designs"=array('label'=array('class'='somecssclass',styles=array(ill add more assoc elements here),'hover'=array(ill add more assoc elements here))))
Javascript version:
{"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
I want to be able to append/modify this array. If 'label' already defined...then cycle through the sub data for that element...and update. If 'label' doesnt exist..then append a new data set to the 'saved_designs' array element.
So, if label is not defined, add the following to the 'saved_designs' element:
array('label2' = array('class'=>'someclass2',styles=array(),'hover=>array()')
Things arent quite working out as i expect. Im unsure of the javascript notation of [], and {} and the differences.
Probably going to need to discuss this as answers are provided....but heres some code i have at the moment to achive this:
//saveLabel = label the user chose for this "design"
if(isUnique == 0){//update
//ask user if want to overwrite design styles for the specified html element
if (confirm("Their is already a design with that label ("+saveLabel+"). Overwrite this designs data for the given element/styles?")) {
currentDesigns["saved_designs"][saveLabel]["class"] = saveClass;
//edit other subdata here...
}
}else{//create new
var newDesign = [];
newDesign[saveLabel] = [];
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
currentDesigns["saved_designs"].push(newDesign);//gives error..push is not defined
}
jQuery("#'.$elementId.'").val(JSON.stringify(currentDesigns));
thanks in advance. Hope this is clear. Ill update accordingly based on questions and comments.
Shaun
It can be a bit confusing. JavaScript objects look a lot like a map or a dictionary from other languages. You can iterate over them and access their properties with object['property_name'].
Thus the difference between a property and a string index doesn't really exist. That looks like php you are creating. It's called an array there, but the fact that you are identifying values by a string means it is going to be serialized into an object in javascript.
var thing = {"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
thing.saved_designs.label is the same thing as thing["saved_designs"]["label"].
In javascript an array is a list that can only be accessed by integer indices. Arrays don't have explicit keys and can be defined:
var stuff = ['label', 24, anObject]
So you see the error you are getting about 'push not defined' is because you aren't working on an array as far as javascript is concerned.
currentDesigns["saved_designs"] == currentDesigns.saved_designs
When you have an object, and you want a new key/value pair (i.e. property) you don't need a special function to add. Just define the key and the value:
**currentDesigns.saved_designs['key'] = newDesign;**
If you have a different label for every design (which is what it looks like) key is that label (a string).
Also when you were defining the new design this is what javascript interprets:
var newDesign = [];
newDesign is an array. It has n number of elements accessed by integers indices.
newDesign[saveLabel] = [];
Since newDesign is a an array saveLabel should be an numerical index. The value for that index is another array.
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
Here explicitly you show that you are trying to use an array as objects. Arrays do not support ['string_key']
This might very well 'work' but only because in javascript arrays are objects and there is no rule that says you can't add properties to objects at will. However all these [] are not helping you at all.
var newDesign = {label: "the label", class: saveClass};
is probably what you are looking for.
Say I have an array of city names, and a MongoDB collection of city names. Say that my array looks like:
["San Francisco", "chicago", "New York", "Los Angeles"]
And my collection looks like
{{cityName: "chicago"}
{cityName: "New York"}}
What I'd like to do is perform a query that returns to me San Francisco and Los Angeles. So far, my only idea is to just perform the query, get the matches, and do an array subtraction from the original array (and thus get my cities), but I wonder if theres a way to do it in a one step query.
Thanks in advance!
You need to perform the following query against your MongoDB collection:
db.cities.distinct("cityName", {cityName:{$in:["new york","los angeles","chicago","san francisco"]}})
This will return the array of cities that matched something in the collection. In your example above you would get back:
["chicago","new york"]
You can now subtract those elements from original array and get the desired result.
The key is to do a distinct query (rather than getting all the results) and pass a query limiting the query to the cities you care about, not all cities that are represented by your collection.
The array subtraction is the only way to go ahead with this as even if you use any mongodb driver and if it supports this function, it will eventually be doing the same thing.
A query on MongoDb will always return the values which are either contained in it or a null value. So you have to take the values and do an array subtraction.
Is there a coma in your collection ?
{{cityName: "chicago"},
{cityName: "New York"}}
If yes, you can do:
for( var i in collec ){
var cityname = collec[i]['cityname'];
// if you use jquery
var getcity = $.grep( yourarray, function(n,i){
return n == cityname;
});
// getcity in an array with all matching elements
console.log(getcity);
}
I have a JavaScript array of objects with the same properties each, something like this:
box[0] = { name: 'somename', /* more properties... */ };
box[1] = { name: 'othername', /* more properties... */ };
box[2] = { name: 'onemorename', /* more properties... */ };
// more objects in the array...
I want to subset this array so that it only contains objects that match a "list" of names and copy the ones that don't to another array named cache maybe. I was thinking maybe I could compare this array of objects to another array which just contains a list of strings with the desired names to match against, checking each object's name property against this list to create a new array with the ones that matched. I don't know if this would work or if it is the best approach to achieve what I want, that is why I am asking for your help. Maybe checking each of 200-500 objects against a list with 100 names is not a very good thing to do, I don't know really.
Do you have any ideas on how I could do this? even better, can you point me to an example?
Thanks in advance.
Assuming the list of names you do want are stored in an array,
var wantedNames = [ "first name", "second name", .. ];
have two arrays - those matching a name and those that don't. Loop through each item in the box object, and if it contains a name from the list, then include it.
var objectsMatchingName = box.filter(function(item) {
return wantedNames.indexOf(item.name) !== -1;
});
var cache = box.filter(function(item) {
return objectsMatchingName.indexOf(item) === -1;
});
I wish there was a array difference operation of some kind, so you could do (in pseudocode):
var cache = box - objectsMatchingName