Access Dictionary Object by String Index - javascript

I am trying to fill a Dictionary (JavaScript object) and retrieve values from it using a string index. For some reason, it always returns undefined when I try to retrieve the values.
My code goes something like this:
var _gauges = {};
//fill the gauges
_gauges[gaugeName] = gaugeObject;
And then I try to get access to it as follows:
setValue: function (gaugeName, newValue) {
var thisGauge = _gauges[gaugeName]; //always undefined
console.log(_gauges); //output shows all the elements that were added to _gauges
if (thisGauge) {
thisGauge.setCell(0, 1, newValue);
}
}
Am I doing anything wrong here?

Ok this was due to a typo... The param that was being passed into the setValue method does not match the one used to add the items to the dictionary object.

Related

Accessing an array inside of JSON object from reviver

I have a JSON object formatted like {"Foo": ["B","A","R"]}
I am trying to access the values of the array like this:
var json = '{"Foo": ["B","A","R"]}';
expression = JSON.Parse(json, function(key, value){
if(key == "Foo"){
console.log(value.length); // logs "3"
console.log(value[1]); // logs "undefined"
}
});
If I ask for the length of value it returns the correct length of the array, but if I ask for the value it returns undefined and I am not quite sure why.There are other values in the JSON that I am able to access just fine, but they are not arrays. Any insight would be appreciated. Thanks!
You should use JSON.parse like this:
var json = '{"Foo":["B","A","R"]}';
var object = JSON.parse(json);
// object is now and object containing the data from 'json'
var expression = object["Foo"][1]; // object["Foo"] refers to the
// value with key "Foo"
(Calling JSON.parse with a callback parameter is an advanced feature for transforming the JSON object, not reading it. In almost all cases, though, you want to use it like the above code, with no callbacks.)
As mentioned in another answer, if you simply want to retrieve the second element of Foo, you can do that easily enough after parsing using standard property access techniques such as obj.Foo[1].
Assuming you really want to use the optional second "reviver" parameter to JSON.parse, you need to return the value from the "reviver" callback;
expression = JSON.Parse(json, function(key, value){
if (key == "Foo"){
console.log(value[1]);
}
return value;
^^^^^^^^^^^^^
});
The reason it appears you can't access value[1] but you can access value.length is (as mentioned by user663031) you don't have a return value.
The reviver function replaces one value with another, if no return is specified all functions will return undefined. The order the reviver receives the values is: first each of the values in the array separately, then the array.
In your code each value has already been replaced with "undefined", so the array has three undefined values as reported by the length. value[1] really is returning the value at position 1 but it is set to "undefined".
When the json string has arrays the reviver function is called with index, [Object] as key, value parameters .
This sniped of code that filter object properties on parse phase will be helpful:
var json = '{"_embedded": [{"a":"A","b":"B","links": {"c":"C"}},{"a":"A2", "b":"B2","links": {"c":"C2"}}]}';
var schemaNames=["_embedded", "a"];
var result= JSON.parse(json, function(k, v) {
console.log(k,v);
if ("" === k){
return v;
}
// On arrays k is a number
else if (schemaNames.indexOf(k) > -1 || !isNaN(k)){
return v;
}
});
console.log(JSON.stringify(result));
Output: {"_embedded":[{"a":"A"},{"a":"A2"}]}
https://jsfiddle.net/pdorgambide/vphbmtk1/
use this code
var json = {'foo' : ['B', 'A', 'R']};
$.each(json, function(key, value){if(key == 'foo'){console.log(value[1]);}});
you already have a json object so no need to parse it again.

Replace String In Object Property Value After Looping Array Javascript

I'm needing to replace a character in an object's property value. I'm looping over the array of objects (outputting to console) and retrieving the FeatureUrl property.
I have data coming back from the Svc for that property in the following form:
index.html#/blah
I'm needing to replace the '#' with '#/app' so that my new url comes back in the following form:
index.html#/app/blah
I'm not sure if .replace is the right method to use here, but it is what I have seen suggested. Can someone point me in the right direction?
var localFeatureDetails = function() {
$scope.user = userService.GetUserInformation();
$scope.featureDetails = $scope.user.Features;
var featureUrlRewrite = function () {
var index;
var urlCount;
for (index = 0; index < $scope.featureDetails.length; index++) {
urlCount = $scope.featureDetails[index];
urlCount.FeatureUrl.replace("#","#/app");
console.log(urlCount);
}
};
featureUrlRewrite();
};
localFeatureDetails();
I did not test your code but based on how .replace() works you have to assign the value to your object property again by overriding it otherwise you're not saving the value.
Assuming everything else is correct, try this:
$scope.featureDetails[index].FeatureUrl = urlCount.FeatureUrl.replace("#","#/app");
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
I think that you might want something more like this
$scope.featureDetails.map(detail => angular.merge({}, detail,
{ FeatureUrl: detail.replace('#', '#/app') }))
instead of the bulky for loop.
we take every detail object out of the featureDetails array, access the FeatureUrl property and replace the # with #/app
.merge(destination, ...sources) merges sources into destination, left-to-right, overwriting properties as it goes.
so angular.merge({}, {foo: 5, bar: 3}, {foo: 7}) would return { foo: 7, bar: 3 }
Removed the console.log() but you can always
console.log($scope.featureDetails);
and then look at the object that is returned in the inspector.

Status of a javascript var after trying to retrieve an unexisting array entry?

Assuming I have a Javascript array and some entries are defined as following:
arr["rrr"]=1;
arr["ee"]=2;
arr["qqq"]=22;
...
Let's assume one tries to retrieve an entry for an unexisting key, for example:
var retr = arr["ppp"];
What is the status of the retr var? Is it null or undefined or something else? How can I check whether the array did not contain a valid entry for the provided key? What is the proper test in Javascript? Thanks.
The result is undefined.
To test you just need to do this:
if ("ppp" in arr) {
// do something
} else {
// do something else
}
The value returned by a missing key is undefined. You can test if the key exists like this :
var a = [];
a.hasOwnProperty('k'); // false
The returned value of the undefined array keys is undefined. The proper test would be
var retr = arr["ppp"];
if(retr!=undefined){
//retr has some value
}
else{
//retr is undefined
}
I tried the code you wrote in Firebug. When I tried to access an entry for an unexisting key
var retr=arr["ppp"];
it returns null. Hence, retr is equal to null.
retr==null; //true
typeof retr=="undefined"; //true

In JavaScript, how to return a part of an Array by reference from a method?

I want to extend the Array.prototype to include a method to select a row or a column from a 2x2 matrix (a list of lists in JavaScript jargon). The method should return by Reference the selected Array elements and thus the result can be used to dynamically change certain values in the Array.
the slice() method of Array doesn't return by Reference
a = [[1,2],[3,4]];
a.slice(0,1) = [0,0];
ReferenceError: invalid assignment left-hand side
My failed attempt
Array.prototype.row = function(whichrow) {
var result = this[whichrow];
return result;
}
It works fine when only the values are needed
a.row(0)
[1, 2]
However, apparently it returns only the value of the row instead of the row itself (if I'm making sense here). So when I try to assign a new value to it, it returns error
a.row(0) = [0,0];
ReferenceError: invalid assignment left-hand side
Anyone has any suggestion?
I'd recommend to implement your row function like this:
Array.prototype.row = function(whichrow, newvalue) {
if( newvalue !== undefined ) {
this[whichrow] = newvalue;
}
return this[whichrow];
}
and use it like this:
a.row(0, [0,0]);
And retrieving:
a.row(0)

How can I store reference to a variable within an array?

I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.
var name = "foo";
var array = [];
array["reference"] = name;
name = "bar";
// Still returns "foo" when I'd like it to return "bar."
array["reference"];
Is there a way to make the array refer to the variable?
Put an object into the array instead:
var name = {};
name.title = "foo";
var array = [];
array["reference"] = name;
name.title = "bar";
// now returns "bar"
array["reference"].title;
You can't.
JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.
If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".
Btw, [] is an array literal. {} is an object literal.
That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.
And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).
Try pushing an object to the array instead and altering values within it.
var ar = [];
var obj = {value: 10};
ar[ar.length] = obj;
obj.value = 12;
alert(ar[0].value);
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called myTarget, then use:
myRef = function (newVal) {
if (newVal != undefined) myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(<the value you want to set>);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray[0]() to read and myArray[0](<new value>) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called 'myTarget', then use:
myRef = function (newVal) {
if (newVal != undefined)
myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(value_to_set);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray0 to read and myArray[0](value_to_set) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.

Categories