Angularjs splitting into array - javascript

I want my data to be stored in an array but mine is stored in a single array, how to split it into like array. This is how it looks like, im spliting it via "|" but i want to store them into array~
JS:
{
$scope.polygonPoints.push($scope.apiResult[i].LatLng)
$scope.polyLineCord.push($scope.polygonPoints[i].split("|"))
console.log($scope.polygonPoints)
for (var k= 0; k < $scope.polyLineCord.length; k++) {
console.log($scope.polyLineCord)
$scope.Lat.push($scope.polyLineCord[k].split(',')[0]);
$scope.Lng.push($scope.polyLineCord[k].split(',')[1]);
L.marker([$scope.Lat[k], $scope.Lng[k]], {icon: greenIcon}).bindPopup($scope.apiResult[k].DESCRIPTION).addTo(cities);
}
}
Sry if the phrasing sounds werid, basically what I want it like "1.309..., 103.844" into array[0] and and "1.30916..., 103.845..." into array1 and so on

You can use es6 features using map for example :
$scope.polygonPoints = ["1.3|1.2|1.5", "1.5|2.2"];
$scope.polygonPoints.map(res => res.split('|'));
result:
["1.3", "1.2", "1.5"] // array one
["1.5", "2.2"] // array two

Related

Push data into existing array using javascript

I am trying to find a way to build my custom array, but I am not able to do so.
What I have done so far:
I have my array constructed like so:
const super_array = [];
super_array.push({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
});
Further down into the code, I want to assign new data to the array, like so :
for(let j=0; j<results.length; j++) {
priceNumber = parseFloat(results[j].replace('<span>Lei</span>', '')) ;
super_array.push({price: priceNumber})
}
Result:
Right now, I get the following structure:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
}, {pret: priceNumber});
What I would like to get is:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit,
pret: priceNumber
});
I am not sure if I have explained it correctly. Basically I want to have the priceNumber uniquely match with the other data in the existing array, and not to be added as a separate index.
super_array[0].pret = priceNumber
super_array.push adds a new object to the array. What you are trying to do in the last code is adding a property to an object of the array.
For example: super_array[0].pret = priceNumber will add the property pret with the value of priceNumber. Here I'm not adding new objects to the array.

javascript json get data names out for object

Still newbie #this, hope not a silly question.
I get from a java backend a json.
For this question I assigned a with that json string.
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
let b=a.data;
let s="";
for (i in b) {s += b[i]};
$('#msg').html(s);
As output I get object Object (small capital, big capital)
In the end I need to run over "data' and print or store that keynames : blablaMOUTI blablaDAN , blablaDAA blablaALHAZO ... on screen or in a simple array list.
The values after the keynames or a empty string, that's fine, I need only the keynames.
Found some semi simular questions, but I don't get it to work. The answers I found all trust I know already the keynames.
You can do it like this:
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
var keys = [];
for(i = 0; i< a.data.length; i++){
for(var k in a.data[i]) {
keys.push(k);
}
}
console.log(keys)
For testing purpose this will populate an array with keys that you wanted, but you can manipulate the result as you wish
Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
Try this:
Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

Hash Tables in javascript

I am trying to build a data structure.
In my limited knowledge, 'hash table' seems to be the way to go. If you think there is an easier way, please suggest it.
I have two, 1-dimensional arrays:-
A[] - contains names of badges (accomplishment)
B[] - contains respective dates those achievements were accomplished from array A[].
An achievement/accomplishment/badge can be accomplished more than one time.
Therefore a sample of the two arrays:-
A['scholar', 'contributor', 'teacher', 'student', 'tumbleweed', 'scholar'.....,'scholar',......]
B['1/2010', '2/2011', '3/2011', '6/2012', '10/2012', '2/2013',......'3/2013',........]
What I want to achieve with my data structure is:-
A list of unique keys (eq:- 'scholar') and all of its existing values (dates in array B[]).
Therefore my final result should be like:-
({'scholar': '1/2010', '2/2013', '3/2013'}), ({'contributor' : ........})..........
This way I can pick out a unique key and then traverse through all its unique values and then use them to plot on x-y grid. (y axis labels being unique badge names, and x axis being dates, sort of a timeline.)
Can anyone guide me how to build such a data structure??
and how do I access the keys from the data structure created.... granted that I don't know how many keys there are and what are their individual values. Assigning of these keys are dynamic, so the number and their names vary.
Your final object structure would look like this:
{
'scholar': [],
'contributor': []
}
To build this, iterate through the names array and build the final result as you go: if the final result contains the key, push the corresponding date on to its value otherwise set a new key to an array containing its corresponding date.
something like:
var resultVal = {};
for(var i = 0; i < names.length; ++i) {
if(resultVal[names[i]]) {
resultVal[names[i]].push(dates[i]);
} else {
resultVal[names[i]] = [dates[i]];
}
}
Accessing the result - iterating through all values:
for(var key in resultVal) {
var dates = resultVal[key];
for(var i = 0; i < dates.length; ++i) {
// you logic here for each date
console.log("resultVal[" + key + "] ==> " + resultVal[key][i]);
}
}
will give results like:
resultVal[scholar] ==> 1/2010
resultVal[scholar] ==> 2/2013
resultVal[scholar] ==> 3/2013
resultVal[contributor] ==> 2/2011
resultVal[teacher] ==> 3/2011
resultVal[student] ==> 6/2012
resultVal[tumbleweed] ==> 10/2012
You can try this...
var A = ['scholar', 'contributor',
'teacher', 'student', 'tumbleweed', 'scholar','scholar'];
var B = ['1/2010', '2/2011',
'3/2011', '6/2012', '10/2012', '2/2013','3/2013'];
var combined = {};
for(var i=0;i<A.length;i++) {
if(combined[A[i]] === undefined) {
combined[A[i]] = [];
}
combined[A[i]].push(B[i]);
}
Then each one of the arrays in combined can be accessed via
combined.scholar[0]
or
combined['scholar'][0]
Note the === when comparing against undefined

Using concatenation and a passed parameter to loop through an array

var Animals = {
"Europe": { "weasel.jpg": "squeak", "cow.jpg": "moo"},
"Africa": { "lion.jpg": "roar", "gazelle.jpg": "bark"},
};
function region(a){
var b = "Animals."+a;
for(var index in b) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
newnode.src = index;
target.appendChild(newnode)
}
}
RELEVANT HTML
<li onclick="europe('Europe')">Europe</li>
Goal: on the click of the Europe <li>, pass the word Europe into my region function where it is then concatenated to produce Animals.Europe
This is in order to identify an array within the object structure at the top using the for(var index in Animals.Europe) loop. Why is the concatenation which produces Animals.Europe not treated in the same way as if I had typed this out?
In addition, you can see that I have used arrays to store an image source and description for different animals. Using my limited coding knowledge this was all I could think of. Is there an easier way to store image/description data in order to produce in HTML?
"Animals." + a is just a string value, e.g. "Animals.Europe", which is not the same thing as Animals.Europe. If you change the first line to var b = Animals[a];, you should be all set.
Edit: and as elclanrs pointed out, it should be region('Europe'), not europe('Europe').
Why is the concatenation which produces Animals.Europe not treated in the same way as if i had typed this out?
In this case the variable b is just a string ("Animals.Europe"), which is treated like any other string (i.e. a list of characters). This means that when you attempt to loop through it (for(index in b)) you will be looping over a simple list of characters.
What you can do instead is use the square brace notation of accessing an objects properties. This means you can instead write var b = Animals[a], retrieving attribute a from Animals. You can read more about working with objects in this way on this MDN page
You can access the europe property using the following
Animals[a]
Also you're calling a "europe" function when you should be calling "region"
You're not storing animals in arrays here, but in objects with the image names as keys. Usually you'll want to use relevant names as keys. For example if you want arrays of animals for each continent
var Animals = {
"Europe": [{
imageSrc: "weasel.jpg",
cry: "squeak"
},{
imageSrc: "cow.jpg",
cry: "moo"
}],
"Africa": [{
imageSrc: "lion.jpg",
cry: "roar"
},{
imageSrc: "gazelle.jpg",
cry: "bark"
}]
};
Now Animals['Europe'] gives an array of objects, where you could eventually store other properties. So if b is an array your loop will now look like:
var b = Animals['Europe'];
for(var i=0; i < b.length; i++) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
var animalData = b[i]; // The array item is now an object
newnode.src = animalData.imageSrc;
target.appendChild(newnode)
}

Looping to Parse JSON Data

Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}
You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...
It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);
Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.

Categories