I am using the immutable Map from http://facebook.github.io/immutable-js/docs/#/Map
I need to get an array of the values out to pass to a backend service and I think I am missing something basic, how do I do it ?
I have tried :
mymap.valueSeq().toArray()
But I still get an immutable data structure back ?
For example :
var d = '[{"address":"10.0.35.118","cpus":4}]';
var sr = JSON.parse(d);
var is = Immutable.fromJS(sr);
console.log(sr);
console.log(is.toArray());
console.log(is.valueSeq().toArray());
See this http://jsfiddle.net/3sjq148f/2/
The array that we get back from the immutable data structure seems to still be adorned with the immutable fields for each contained object. Is that to be expected ?
Just use someMap.toIndexedSeq().toArray() for getting an array of only values.
It's because the sr is an Array of Object, so if you use .fromJS to convert it, it becomes List of Map.
The is.valueSeq().toArray();(valueSeq is not necessary here.) converts it to Array of Map, so you need to loop through the array, and convert each Map item to Array.
var d = '[{"address":"10.0.35.118","cpus":4}]';
var sr = JSON.parse(d);
// Array of Object => List of Map
var is = Immutable.fromJS(sr);
console.log(sr);
console.log(is.toArray());
// Now its Array of Map
var list = is.valueSeq().toArray();
console.log(list);
list.forEach(function(item) {
// Convert Map to Array
console.log(item.toArray());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.min.js"></script>
Map.values() returns an ES6 Iterable (as do Map.keys() and Map.entries()), and therefore you can convert to an array with Array.from() or the spread operator (as described in this answer).
e.g.:
Array.from(map.values())
or just
[...map.values()]
Related
I am trying to iterate over an array of array objects to de-dupe and sort the data within each. The function onlyUnique returns unique values in an array. The problem is, it doesn't work as intended.
arr_lists = [arr_1, arr_2, arr_3, arr_4, arr_5, ...]
for (var list_obj of arr_lists) {
list_obj = list_obj.join().split(',').filter(onlyUnique);
list_obj.sort();
Logger.log(list_obj);
}
The logger results show true (i.e. they are what I am looking for), but the original array is unchanged, although I think it should have been updated.
I've tried assigning the filtered array to a new array... nope.
I know that I could add a thousand lines of code to achieve the results, but that seems silly.
I suspect it's something obvious.
You can simply achieve it by using Set data structure to remove the duplicates and Array.sort() compare function to sort the elements in an array.
Live Demo :
const arr_lists = [[2,3,5,6], [7,2,5,3,3], [1,5,3], [4,7,4,7,3], [1,2,3]];
arr_lists.forEach((arr, index) => {
arr_lists[index] = [...new Set(arr)].sort((a, b) => a -b);
})
console.log(arr_lists);
I use list comprehension often in Python specifically to create a list from a dictionary of key values, in a sorted manner, I define the sorted keys in a list and use comprehension to get a sorted list, I have been looking around but could not find a similar method of doing the following in Javascript other than using a map:
Is there a better way to do this in Javascript?
In Python:
d = {'k2':'v2','k4':'v4','k3':'v3','k6':'v6','k5':'v5'}
list_keys=['k1','k2','k3','k4','k5','k6']
list_wanted_values = [d[c] for c in list_keys]
#list_wanted_values=['v1','v2','v3','v4','v5','v6']
In Javascript:
var js_list_wanted_values = list_keys.map(function(k){
js_list_wanted_values[k] = d[k]
)}
maybe this
var js_list_wanted_values = list_keys.map(k => d[k])
Your map should be more like
var js_list_wanted_values = list_keys.map(function(k){
return d[k]
})
map() creates a new array by returning a new value based on value of each element in array being iterated
i want to convert a json array (string) to javascript array using just some specific values. The json array is :
[{"id":47,"libelle":"famille de test"},{"id":1,"libelle":"GEOLOCALISATION"},{"id":4,"libelle":"OUTILS"},{"id":2,"libelle":"PROPRETE"},{"id":3,"libelle":"URGENCE"}]
and i want to get something like this ["famille de test", "GEOLOCALISATION", ...] using just libelle values.
I tried to use $.map but didn't work out.
The map implementation should work:
var jsonStr = '[{"id":47,"libelle":"famille de test"},{"id":1,"libelle":"GEOLOCALISATION"},{"id":4,"libelle":"OUTILS"},{"id":2,"libelle":"PROPRETE"},{"id":3,"libelle":"URGENCE"}]';
var arr = JSON.parse(jsonStr);
var libelle = arr.map(function(x) { return x.libelle; });
First, you must turn your JSON string into a JavaScript Array by using JSON.parse(yourJSONString). After that, it is a simple JavaScript array and you can use the map method you tried
Couldn't think of better title.
Important to note: I'm new to js and I guess its the reason I can't figure it out by myself.
I have a JSON array returned from a database, the JSON array represent a set of points.
Example of the JSON array:
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...]
I want to make a different array whose elements will be a function and the variables of the function will be the elements from the JSON array, like so:
var coordinates = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(1, 3),
new google.maps.LatLng(2, 3),
....
];
I made a function using forEach that counts the elements of the JSON array (for learning and trying to find a way to what I want) but I cant think of a way make the array mentioned above.
You could use Array map method:
var coordinates = JSON_array.map(function(coordinate) {
return new google.maps.LatLng(coordinate.lat, coordinate.lng);
})
This method gives you an new array based on (1) the original array and (2) how you deal with each element. Here's more detailed doc for the method.
you can also use regular for loop
coordinates = [];
for(var i=0;i<JSON_array.length;i++){
coordinates.push(new google.maps.LatLng(JSON_array[i].lat,JSON_array[i].lng));
}
For mapping element from one array to another you can use Array.prototype.map function like
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...];
var coordinates = JSON_array.map(function(el){ return new google.maps.LatLng(el.lat, el.lng)});
As Grundy commented you can just do:
coordinates = JSON_array.map(function(x) {
return new google.maps.LatLng(x.lat, x.lng);
});
You might want to get your nomenclature straight though, this has nothing to do with JSON.
I am storing some values in array like this.
var test = [];
I am pushing the values to this array as test.push(sample);
I have some logic for calculating this value
var sample= (a/b.length)*100;
When I click on a button, the above logic for calculating value of sample is done and once I got the value of sample I am pushing it to test[] array. Now I want to retrieve all the values from the test[] array whenever I check the checkbox. I am able to do all this but I am facing a problem here. only the last pushed value is saving. but I want to save all the values that are being pushed. can anyone please help me in solving this issue.
Quick response is needed and appreciated
Regards
Hema
You need to use 2 dimensional array for this.
Use
var test= new Array();
then assign value test['someKey']=sample;
or test.push(sample); . you can retrieve array value like alert(test[0]) or by iterating array with $.each(test,function(index,value){alert(value)});
What you want to do is create an Array which would function as a list of value sets.
You would then be able to push all the changes into an array, and put it in the list.
for instance:
var mainList = new Array();
var changeListA = new Array();
var changeListB = new Array();
// do some stuff on change list **a** .. push(something)
changeListA .push(something);
changeListA .push(something);
changeListA .push(something);
// do some stuff on change list **b** .. push(something)
changeListB .push(changeListB);
mainList.push(changeListA);
Your question is not perfectly clear to me, however I can at least provide a small jsFiddle that proves to you that (how) array.push works.
Other answers indicate that what you want is either a two dimensional array, or a "hashmap" or "associative array" where the array values are stored using a key name. The code here can be used in the fiddle to achieve either or...
http://jsfiddle.net/xN3uL/1/
// First if you need 2 dimensional arrays:
myArray.push( ["Orange", "Apple"] );
myArray.push( ["Mango", "Pineapple"] );
// Secondly, if you need hashmap or associative array:
var myObj = {};
myObj['key'] = 'value';
alert(myObject.key);