Creating object with varying keys - javascript

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.

Related

getting the value/key from a dynamic map object in immutable.js

I have a dynamic immutable object and I want to know a better way to get a deep-level value. Fiddle Example
var map = {aaa:{bbb:{ccc:'ddd'}}}
map = Immutable.fromJS(map)
Suppose that I don't know the third-level key ccc, what is the best way to get its value, which in this case ddd?
var map = {aaa:{bbb:{ccc:'ddd'}}}
map = Immutable.fromJS(map)
map.keySeq().toList().map(first=>{
map.get(first).keySeq().toList().map(second=>{
map.getIn([first,second]).valueSeq().toList().map(third=>{
alert(third)
})
})
})
Is the above example an appropriate way to get the value ddd. I can't simply use map.getIn(['aaa','bbb','ccc']) because this map object is dynamic in my situation
As I understand, you're trying to obtain the key which has ddd value. If you're aware of the object nesting levels, you can simply flatten it.
var map = {aaa:{bbb:{ccc:'ddd'},eee:{fff:'ggg'}}};
var map = map.flatten(3);
/// {
/// ccc: "ddd",
/// fff: "ggg"
/// }
Now, simply filter the map and obtain requisite key.

how to create a map in javascript with array of values dynamically

I have this requirement. Depending on the number of arguments passed in the function, I need to create that many entries in my map. Say I have a function myfunc1(a,b,c) , I need to have a map with the keys as "a","b" and "c" and I can have more than one values for each of the keys. But the problem is that I do not know beforehand, how many values will come for those keys. As and when the values come, I need to add them to the list of values corresponding to the matching key in the map. How do I do this in javascript? I have found static answers like below. But I want to do this dynamically. Can we use the push method ?
var map = {};
map["country1"] = ["state1", "state2"];
map["country2"] = ["state1", "state2"];
I think this is what you are asking. addValueToList will create array/list dynamically if the key is not present in the map.
//initially create the map without any key
var map = {};
function addValueToList(key, value) {
//if the list is already created for the "key", then uses it
//else creates new list for the "key" to store multiple values in it.
map[key] = map[key] || [];
map[key].push(value);
}
You can use the arguments list to populate your object with key corresponding to the strings passed in as arguments. Then you can write another function to populate this map with data.
var createMap = function() {
var map = {};
Array.prototype.slice.call(arguments).forEach(function ( arg ) {
map[arg] = null;
});
return map;
}
So createMap('para1', para2', para3') will return an object with 3 keys: para1, para2, para3. All having null as value. You can obviously replace null with a reference to the data you want the key to have, if you want to do it all in one function.

angularjs : iterate array with key value pairs

I am creating an array like the following:
var arr =[];
arr['key1'] = 'value1';
arr['key2'] = 'value2';
If is use this array in ng-repeat tag, it is not displaying anything. Is there any way to make it work?
<div data-ng-repeat='(key,value) in arr'>{{key}} - {{value}}</div>
Is there any way to make it work?
The way to go, is to creat plain object (instead of array)
// instead of creatin of an Array
// $scope.myArr = [];
// we just create plain object
$scope.myArr = {};
...
// here we just add properties (key/value)
$scope.myArr['attempt1'] = {};
...
// which is in this case same as this syntax
$scope.myArr.attempt1 = {};
Thee is updated plunker
Check more details what is behind for example here:
Javascript: Understanding Objects vs Arrays and When to Use Them. [Part 1]
Your associative array is nothing but an object, as far as JavaScript is concerned. IMO Associative arrays and Objects are almost same.
Ex: Your arr['key1'] = 'value1'; can be called as console.log(arr.key1);
To make your code work, you need to change the array declaration by removing [] and replacing with {} (Curly braces)
Like this var arr = {};

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

JavaScript concat not working as expected, care to elaborate?

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]);

Categories

Resources