How to make an array from JSON? - javascript

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.

Related

List comprehension based on a dictionary in Javascript

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

Building a 2D Array in Javascript

I've been trying to build a 2D array in javascript, but not having much success. I'm pulling some data from a DB and I then want to combine some fields into a 2D array in order to use it elsewhere in the code. Ideally what I want to end up with is:
mapLocs = [
['name a','location a',1],
['name b','location b',2],
['name c','location c',3]
]
here is the code I am using to build the mapLocs array:
for(i = 0;i < phtLen;i++){
var x = i + 1;
var myLocs = new Array(myPhotogs[i].phtName,myPhotogs[i].phtLoc,x);
console.log(myLocs);
mapLocs[i] = new Array(myLocs);
}
}
which is pretty much the method that I've gathered from reading similar problems here. The console.log() outputs an array consisting of the three elements I want, but if I try to access mapLocs it doesn't seem to consist of three arrays as I would have expected, but of three elements each of which is made up of the three elements in the myLoc array if that makes sense? So:
console.log(mapLocs[0][0]); // Joe Bloggs, SW1A 1AA, 1
where I was expecting just 'Joe Bloggs' and
console.logs(mapLocs[0][1]); // undefined
What am I doing wrong?
The explicit new Array() constructor does not take an array and make a new array identical to the argument array, but takes a list of arguments that you wish to be contained within the new array. So in the line
mapLocs[i] = new Array(myLocs)
mapLocs[i] is actually being set to
[[Joe Bloggs, SW1A 1AA, 1]]
Instead, you could say
mapLocs[i] = myLocs.slice()
which will clone myLocs and place it at index i in mapLocs, resulting in the output you want.

how to push data to existing sapui5 model

I have a Json Model in sapui5 as - //console.log(dModel);
My new data response is as follows - //console.log(response);
Now I want to push new data(only the data part) to the existing model, inside /modelData/data.
code I am trying -
sap.ui.getCore().getModel().getProperty("/modelData/data").push(response.data);
This code is pushing the data but as -
After 19(old values) it is pushing all the objects inside 20th as 0, 1, 2... The Ideal way should be after 19 I should get 20, 21, 22 and so on.
What changes I need to make to get this, Thank you ... please suggest.
If you need to add new items to your model, you should use it like this:
var oModel = sap.ui.getCore().getModel();
var aData = oModel.getProperty("/modelData/data");
aData.push.apply(aData, response.data);
oModel.setProperty("/modelData/data", aData);
The difference is you first retrieve the array with data, add to the array, and then set the property with the updated array
Edit: Ok, makes sense now: you are adding an array to an array. And using 'push' just adds a new entry with whatever object you are adding. So you are adding a single entry (which happens to be an array)
See updated answer
Try this:
for(var i = 0; i < response.data.length; i++){
sap.ui.getCore().getModel().getProperty("/modelData/data").push(response.data[i])
}

Immutable.js Map values to array

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

push values into an array dynamically with javascript

I'm have trouble finding a way to push values into an array dynamically. I have given the following situation:
var get_anchors= new Array('pitzel','mitzel','sizzle')
current_anchor= pics[key].anchor; //has the value 'sizzle'
get_anchors[current_anchor].push(new Array('sizzle2','sizzle3'))
Javascript fails and says get_anchors[current_anchor] is undefined
How can I make get_anchors[current_anchor] work. Or is there a different way to get this done?
The desired result should look like 'pitzel','mitzel','sizzle'['sizzle2','sizzle3]
Based on your comment it looks like you want a hash map instead of an array. You can use an object for this:
var anchors = {
'pitzel': [],
'mitzel': [],
'sizzle': []
};
Then you can do:
anchors[current_anchor].push('sizzle2', 'sizzle3');
or assuming that anchors does not have a property with the value of current_anchor, simply assign a new array:
anchors[current_anchor] = ['fooX', 'fooY'];
Of course you can populate the object dynamically as well. Have a look at Working with Objects for more information.
I'm not sure I understand what you're trying to do, but I think you're trying to insert a few elements after where another occurs. This will do the trick:
var get_anchors = [ 'pitzel', 'mitzel', 'sizzle' ];
current_anchor = get_anchors.indexOf(pics[key].anchor);
get_anchors.splice(current_anchor + 1, 0, 'sizzle2', 'sizzle3');
// get_anchors = [ 'pitzel', 'mitzel', 'sizzle', 'sizzle2', 'sizzle3' ]

Categories