Reading an object's value in JavaScript - javascript

I want to get the features from my layer. So I'm requesting WMSGetFeatureInfo method after a successful request for GetFeatureInfo on my layer.
The returned object is structured like this:
I can read values like BEVDICHTE with var bevdichte = features.BEVDICHTE and so on.
But when I want to get the value of the_geom with var the_geom = features.the_geom it returns an object. Yes it is nested so this is intended but my question is how to get the value ol.geom.MultiPoint
from the_geom?
EDIT:
Unfortunately var target = features.the_geom['actualEventTarget_']; will just return another 'actualEventTarget_' object. This is because the the_geom object is nested into infinity. I attached another screenshot to describe my problem. There are many more nested eventTargets following. Yet I was not able to get the property ol.geom.MultiPolygon.

To access a nested array, just use brackets: '[ ]'
var nestedArray = [[1,2], [3,4]];
var nestedArrayValue = nestedArray[0][0];
// --> returns 1
With your example:
var target = features.the_geom['actualEventTarget_']
By the way, from the looks of it var the_geom = features.the_geom doesn't seem like an array. It has keys, mapped to a value, are you sure this is an array, not an object?

Related

find value in complex object javascript

Basically I have a complex object that retrieves the GPT API (google publisher tag) with this function:
googletag.pubads().getSlots();
The object value is something like this:
I need to know if there is a way to compare the value of each property with an X value without getting a problem of recursivity (because the object is huge and i need to to that validation several times)
Also, I tried to convert that object into a JSON with JSON.stringify(), and then tried to get the value with a regex, faster, but with this option, I have the problem with Cyclic Object Value.
Any suggestions ?
it's more simple. try it to convert it into an array and later use a filter for comparative with your value.
var objGoogle = {};
var arrayObjectGoogle = [objGoogle];
var filter = arrayObjectGoogle.filter(function(obj){
obj.yourAttr == yourValue; });
this will give you a second array with the values found it. later, index the array for pick up the value do you need.

Javascript object/array manipulation

Struggling with some javascript array manipulation/updating. Hope someone could help.
I have an array:
array('saved_designs'=array());
Javascript JSON version:
{"saved_design":{}}
I will be adding a label, and associated array data:
array("saved_designs"=array('label'=array('class'='somecssclass',styles=array(ill add more assoc elements here),'hover'=array(ill add more assoc elements here))))
Javascript version:
{"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
I want to be able to append/modify this array. If 'label' already defined...then cycle through the sub data for that element...and update. If 'label' doesnt exist..then append a new data set to the 'saved_designs' array element.
So, if label is not defined, add the following to the 'saved_designs' element:
array('label2' = array('class'=>'someclass2',styles=array(),'hover=>array()')
Things arent quite working out as i expect. Im unsure of the javascript notation of [], and {} and the differences.
Probably going to need to discuss this as answers are provided....but heres some code i have at the moment to achive this:
//saveLabel = label the user chose for this "design"
if(isUnique == 0){//update
//ask user if want to overwrite design styles for the specified html element
if (confirm("Their is already a design with that label ("+saveLabel+"). Overwrite this designs data for the given element/styles?")) {
currentDesigns["saved_designs"][saveLabel]["class"] = saveClass;
//edit other subdata here...
}
}else{//create new
var newDesign = [];
newDesign[saveLabel] = [];
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
currentDesigns["saved_designs"].push(newDesign);//gives error..push is not defined
}
jQuery("#'.$elementId.'").val(JSON.stringify(currentDesigns));
thanks in advance. Hope this is clear. Ill update accordingly based on questions and comments.
Shaun
It can be a bit confusing. JavaScript objects look a lot like a map or a dictionary from other languages. You can iterate over them and access their properties with object['property_name'].
Thus the difference between a property and a string index doesn't really exist. That looks like php you are creating. It's called an array there, but the fact that you are identifying values by a string means it is going to be serialized into an object in javascript.
var thing = {"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
thing.saved_designs.label is the same thing as thing["saved_designs"]["label"].
In javascript an array is a list that can only be accessed by integer indices. Arrays don't have explicit keys and can be defined:
var stuff = ['label', 24, anObject]
So you see the error you are getting about 'push not defined' is because you aren't working on an array as far as javascript is concerned.
currentDesigns["saved_designs"] == currentDesigns.saved_designs
When you have an object, and you want a new key/value pair (i.e. property) you don't need a special function to add. Just define the key and the value:
**currentDesigns.saved_designs['key'] = newDesign;**
If you have a different label for every design (which is what it looks like) key is that label (a string).
Also when you were defining the new design this is what javascript interprets:
var newDesign = [];
newDesign is an array. It has n number of elements accessed by integers indices.
newDesign[saveLabel] = [];
Since newDesign is a an array saveLabel should be an numerical index. The value for that index is another array.
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
Here explicitly you show that you are trying to use an array as objects. Arrays do not support ['string_key']
This might very well 'work' but only because in javascript arrays are objects and there is no rule that says you can't add properties to objects at will. However all these [] are not helping you at all.
var newDesign = {label: "the label", class: saveClass};
is probably what you are looking for.

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 = {};

Creating Nested Objects on the Fly With Javascript

I'm new to Javascript coming from a Python background, where it's easy to created nested data using custom dictionaries and .get methods. What I'm trying to do is created a nested object of artist data that takes on this form: artistDict[artist][albumName] = albumYear. I need to create this object on the fly by iterating over an iterable of album objects. Here's the code I'm currently using:
albumDict = {};
albums.forEach(function(item){
albumDict[item.artist][item.name] = item.year;
});
document.write(albumDict);
This doesn't work, which isn't surprising, since something like this wouldn't work in Python either. However, in Python I could use a .get method to check if an entry was in the dictionary and create it if not -- is there something similar, or any other utility that I could use to achieve my goal in JS?
This should work: (if the property doesn't exist you should initialize it..)
albumDict = {};
albums.forEach(function(item){
albumDict[item.artist] = albumDict[item.artist] || {};
albumDict[item.artist][item.name] = item.year;
});
Try this:
albums.forEach(function(item){
albumDict[item.artist] = albumDict[item.artist] || {};
albumDict[item.artist][item.name] = item.year;
});
The first line in that function sets albumDict[item.artist] to a new object if it doesn't exist, yet. Otherwise, it sets it to itself.
Then, you can just set the year on the dict entry.

Test for value within array of objects

I am dynamically building an array of objects using a process that boils down to something like this:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"id":"foobar_1", "metrics":90};
var object2 = {"id":"some other foobar", "metrics":50};
objects[0] = object1;
objects[1] = object2;
(Let it be said for the record, that if you can think of a better way to dynamically nest data such that I can access it with objects[i].id I am also all ears!)
There's ultimately going to be more logic at play than what's above, but it's just not written yet. Suffice it to say that the "object1" and "object2" parts will actually be in an iterator.
Inside that iterator, I want to check for the presence of an ID before adding another object to the array. If, for example, I already have an object with the ID "foobar_1", instead of pushing a new member to the array, I simply want to increment its "metrics" value.
If I wasn't dealing with an array of objects, I could use inArray to look for "foobar_1" (a jQuery utility). But that won't look into the object's values. The way I see it, I have two options:
Keep a separate simple array of just the IDs. So instead of only relying on the objects array, I simply check inArray (or plain JS equivalent) for a simple "objectIDs" array that is used only for this purpose.
Iterate through my existing data object and compare my "foobar_1" needle to each objects[i].id haystack
I feel that #1 is certainly more efficient, but I can't help wondering if I'm missing a function that would do the job for me. A #3, 4, or 5 option that I've missed! CPU consumption is somewhat important, but I'm also interested in functions that make the code less verbose whether they're more cycle-efficient or not.
I'd suggest switching to an object instead of an array:
var objects = {};
objects["foobar_1"] = {metrics: 90};
objects["some other foobar"] = {metrics: 50};
Then, to add a new object uniquely, you would do this:
function addObject(id, metricsNum) {
if (!(id in objects)) {
objects[id] = {metrics: metricsNum};
}
}
To iterate all the objects, you would do this:
for (var id in objects) {
// process objects[id]
}
This gives you very efficient lookup for whether a given id is already in your list or not. The only thing it doesn't give you that the array gave you before is a specific order of objects because the keys of an object don't have any specific order.
Hmm , i wonder why dont you use dictionary cause that is perfectlly fits your case. so your code will be as below:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"metrics":90};
var object2 = {"metrics":50};
objects["foobar_1"] = object1;
objects["some other foobar"] = object2;
// An example to showing the object existence.
if (!objects["new id"]){
objects["new id"] = {"metrics": 100};
}
else {
objects["new id"].matrics++;
}

Categories

Resources