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

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.

Related

Creating object with varying keys

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.

comparing two maps and adding key to one map in javascript

I have two maps named maps1 and list1, and how do I compare their object and if the object is same, the key for maps1 goes for list1's key in javascript.
I know that to add values in map, the code is written
map1[anykey] = value;
If map1 contains {hi , hello}, {a, b}, {c, d}
and list1 contains [hi, a], I want to finally make a map2 that resembles something like this: {hi, hello}, {a, b}. is this anyway possible?
Just create a new, blank map object, loop through the list array, and copy over any properties whose names are in it:
// Create the blank object
var newObject = Object.create(null); // Or just {} if you prefer
// Loop through the array
list.forEach(function(name) {
// Does the original object have a property by this name?
if (name in originalObject) {
// Yes, copy its value over
newObject[name] = originalObject[name];
}
});

Alternatives to comparing object property using if...else

I hope I make my question clear.
I have a few objects which I have created with a property called address. For example, Obj1 has address 0x0000, Obj2 has address 0x0004 and so on.
There is a list of random input addresses which I need to process. Once the input address is one of the object address (if addr=0x0000||addr=0x0004....), then a function will be automatically loaded.
Currently, I am comparing it by a list of Object addresses, which I think is a waste of iteration. Is there any way, I can access it by index? For example, once I enter an input address of 0x0004, a function will be run directly.
edit : Thanks for all your answers :) I have a clearer idea now
You got 2 choices:
Use switch to define all functions:
switch (input){
case '0x0000': function(input){}; break;
case ...
}
Use a predefined map:
var functionMappings = {
'0x0000': function_1,
'0x0001': function_2,
};
if(functionMappings[input]) {
functionMappings[input](input);
}
I would prefer the second example, because it can be created dynamically in the runtime.
Update:
You can create your functionMappings dynamicaly like this:
var functionMappings = {// create first entries, or defualt functions
'0x0001': function_1,
'0x0002': function_2
};
if(condition_x) { // add new or overwrite existing functions
functionMappings[0x0005] = function_5;
}
Because this is an map, you can even overwrite default function definitions, if you need.
Iterate once and put all addresses as keys to an object:
var addresses = {};
for(var i=0;i<objList.length;i++){
addresses[objList[i].addr] = {};
addresses[objList[i].addr].fn = correspondingFunction
// you can even attach the corresponding object to it
// addresses[objList[i].addr].obj = addresses[objList[i].addr];
}
I use a loop for the example but you can do it any way that suits you
Then you have a list of your objects keyed by their address, and you can fetch them by it:
function getAddrFunction(addr){
if(addresses[addr] !== undefined){
return addresses[addr].fn;
}
return null;
}

How to store number of object element of array in another array?

im trying to store some object element from one array to another so lets say i have this array of objects
var Array = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
and i want to store the first two object in this array to another array so it would like be
var SubArray =[{name:'Fadi'},{name:'Joseph'}];
thanks in advance for any help.
You can use slice method for this:
var SubArray = Array.slice(0,2);
Please note that Array is reserved JS global object. You need to use different name for that variable. So your code should be for example:
var MyArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var SubArray = MyArray.slice(0,2);
If you need conditional logic you want Array.filter(). If you know you always want the items by index then use slice as in antyrat's answer.
var originalArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var subArray = originalArray.filter(function(obj,index) {
return obj.name=="Fadi" || obj.name=="Joseph";
})

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.

Categories

Resources