Using variable keys to access values in JavaScript objects - javascript

The code:
function updateDashboardData() {
$.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
$('.stationContainer').each(function(data) {
var bsID = $(this).attr("id");
var bsStatus = $(this).children('.stationStatus');
alert(data[bsID][0].time);
bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
bsStatus.find('.bs_time').text(data[bsID][0].time);
});
});
}
The object data:
{
"A5A50000": [{
"bsid": "A5A50000",
"chanCount": 17,
"time": "2009-05-27 16:36:45",
"avgInterference": 1.711765,
"maxInterference": 4.97,
"avgHandsets": 205.1176,
"maxHandsets": 315,
"avgCalls": 6.4118,
"maxCalls": 13,
"avgCBA": 3868.98059,
"maxCBA": 7463,
"sumSuccessCBA": 197318,
"sumTimeoutHandoff": 133,
"sumAttemptHandoff": 1028,
"sumDeniedHandoff": 216,
"sumConfirmHandoff": 679,
"sumHandoffNetwork": 61873,
"sumJoinNetwork": 96888,
"sumLeaveNetwork": 93754,
"sumRcvdKeepalive": 98773,
"sumTimeoutKeepalive": 19748,
"sumAttemptUplink": 93689,
"sumBlockedUplink": 62453
}]
}
The problem:
alert(data.A5A50000[0].time); properly displays "2009-05-27 16:36:45".
alert(bsID); properly displays "A5A50000".
alert(data.bsID[0].time); reports "data.bsID is undefined".
alert(data[bsID][0].time); reports "data[bsID] is undefined".
I'm a little unclear when a variable is/isn't evaluated. Maybe I'm overlooking something silly, but I can't figure out my problem here.

You can access object properties by dot notation or by bracket notation.
var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi
When you have a dynamic value, you have to use the latter:
var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi
So what you actually want is:
alert(data[bsID][0].time);
EDIT:
Not sure what you're doing wrong, but this is working for me on Firebug's console:
var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]};
var bsID = 'A5A50000';
alert(data[bsID][0].time);

In Javascript, you can use either object or array-style notation to look up an attribute. The following are equivalent:
data.A5A50000
data['A5A50000']
With the second syntax, you can use a variable in place of an object string:
data[bsID][0]

I experienced the same problem with a nested JSON API-response:
[
{
"bj_code": "2019",
"BJ_PERIODE": [
{
"nummer": 1
},
{
"nummer": 2
}
]
}
]
I could evaluate:
pm.expect(pm.response.json()[0].BJ_PERIODE[1].nummer).to.eql(2);
But working with BJ_PERIODE and nummer through a variable didn't work.
Writing it with the bracket method did work, even in this nested JSON, like this:
const periode = "BJ_PERIODE";
const nr = "nummer";
pm.expect(pm.response.json()[0][periode][1][nr]).to.eql(2);

Related

json.stringify(obj) error obj is not defined

I'm trying to access an element of an object but whenever I do the code throws an undefined error.
var pokeShow= function(pokaName,datapp) {
for(var i=0;i<datapp.pokemon.length;i++) {
if(datapp.pokemon[i].name==pokaName){
var dispo=datapp.stringify(pokemon[i]) // this line is showing error that pokemon is not defined
alert(dispo)
}
else
alert("wrong input")
}
the json file(a block of it):-
var pokeData = {
"pokemon": [{
"id": 1,
"num": "001",
"name": "Bulbasaur",
"img": "http://www.serebii.net/pokemongo/pokemon/001.png",
"type": [
"Grass",
"Poison" ...
Pokemon seems to be clearly defined in the object, why is this error being thrown?
It seems you are trying to get part of an object that you haven't defined as it's own.
datapp.pokemon[i].name==pokaName
pokemon[i]
Try replacing
var dispo=datapp.stringify(pokemon[i])
with
var dispo=datapp.stringify(datapp.pokemon[i])
Also, I am not entirely sure but I think you meant to put JSON.stringify instead of datapp.stringify
for(var i=0;i<datapp.pokemon.length;i++) {
if(datapp.pokemon[i].name==pokaName){
var dispo=datapp.stringify(pokemon[i])
alert(dispo)
}
}
pokemon is an array which is part of datapp, which you're doing right when you're comparing if(datapp.pokemon[i].name==pokaName). The problem is when you stringify it, you're not referring to datapp.pokemon[i] and hence the undefined. Instead you can change it to below
var dispo=JSON.stringify(datapp.pokemon[i])

angularjs replace newline from an object copied with angular.copy()

I am trying to replace all line breaks in an object property which is being filled using angular.copy from a json object but for some reason the value can not be modified.
angular.copy(data, vm.candidate);
console.log(vm.candidate.Comments.replace(/\n/g, '<br/>'));
The output is still: hi\nhow\nare\nu\n
But if I set this output in a variable
var xx = "hi\nhow\nare\nu\n";
console.log(xx.replace(/\n/g, '<br/>'));
The output is: hihowareu as expected.
Basically, I am trying to do something like this:
vm.candidate.Comments=$sce.trustAsHtml(vm.candidate.Comments.replace(/\n/g, '<br/>'));
In the view:
<p ng-bind-html="candCtrl.candidate.Comments"></p>
Trying to get the right outoput in the view:
"hi how are u"
Any ideas why it is not working?
A jsfiddle example: jsfiddle
*Notice, I'm working with the jsfiddle provided in the comments to the original question.
Basically, you're using angular.copy wrong.
According to the angular docs at here:
[angular.copy] Creates a deep copy of source, which should be an object or an array.
You're trying to copy a string.
The solution is to copy the entire object and then use your regex to replace \n with <br/>
your code:
function LoginController($scope) {
$scope.car2 = {};
$scope.car = { "ID": 3, "Comments": "hi\\nhow\\nare\\nu\\n","RatingID": 2,"Rating":"Unsure"};
$scope.car2=angular.copy($scope.car.Comments.replace(/\n/g, '<br/>'));
}
working code (jsfiddle):
function LoginController($scope) {
$scope.car2 = {};
$scope.car = { "ID": 3, "Comments": "hi\nhow\nare\nu\n","RatingID": 2,"Rating":"Unsure"}
$scope.car2 = angular.copy($scope.car)
$scope.car2 = $scope.car2.Comments.replace(/\n/g, '<br/>')
}

Add [DataObject] to exsisting array with var key

Using Cordova, I am trying to get an Object to add to an array. I have this working on node JS using :
theData = {[varkey]:DataObject};
But I can't get this to work the same way within my javascript that cordova runs.
I need to do the following:
var TownName = 'Auckland', var townData = (JSON Data);
theArray = new Array();
theArray[TownName] = townData;
I need to be able to call it back as:
theArray['Auckland']
Which will return (JSON Data)
But it doesn't want to store the data with the key inside the array.
I have also tried:
theArray.TownName = townData;
theArray = [{TownName:townData}];
theArray = {[TownName]:townData}];
Nothing wants to store the data.
Any suggestions?
::EDIT::
data.theData =
"Auckland"[
{
"username":"pndemoname1",
"number":"373456",
"www":"http://373456.pndemoname1",
"icon":"/imgs/pndemoname1.png"
},
{
"username":"pndemoname2",
"number":"373458",
"www":"http://373458.pndemoname2",
"icon":"/imgs/pndemoname2.png"
}
data.town = "Auckland";
townData = new Array();
alert(JSON.stringify(data.theData))//Alerts theData
townData[data.town] = data.theData
alert(townData[townName]) //Alerts undefined
::EDIT2::
Re-defining the array within the function that deals with all of the data, seems to make it work.
As per my answer, the issue was that I assumed javascript vars are global.
Use objects or an array of objects.
A data structure like this:
{
town1: town1Data,
town2: town2Data,
}
Or more common:
[
{
name: "Town 1",
data: {...}
},
{
name: "Town 2",
data: {...}
},
]
For reference:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
I got what you're trying to do, to add property names dynamically to your object is first, by making sure you are using an OBJECT instead of an array, so when you want to store something you will do the following:
var _obj = {}, _something = 'xyz';
_obj[ _something ] = { ... }; // json structure
The problem you're facing is that you want to assign a string value as a key inside your array, which will not work.
However, you can still use the array you defined and do the following:
var _array = new array();
_array.push( { .... } ); // insert json structure
Remember! By using the array you will have to loop through all values every time you want to access your key, just as the best practice to avoid getting into errors.
Good luck.
The issue was that I didn't define the array within the function of where I was trying to add the information to.
I assumed the var was global (Too much PHP)

Addressing a String variable inside a Json with javascript

I'm new with Javascript and bumped into a funny problem.
I have a Json which is alike the following:
{
"TEAM-8f382740": {[
{info1},
{info2},
{info3}
]}
}
I'm trying to get the content behind that "TEAM-8f382740" in my code:
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
.success(function(data) {
$scope.champs = data.??; //what to put here to get just {info1},{info2}...
});
Problem is the 'TEAM-8f382740' is a variable and the same time in a tricky form.
I tried the following:
$scope.teamName = 'TEAM-8f580740'; //or var teamName='TEAM-8f580740';
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
.success(function(data) {
$scope.champs = data.$scope.teamName; //data.teamName doesn't work either
});
So how to get that [{info1},{info2},{info3}] content from the Json?
I tried with other kind of Jsons and seems if instead of "TEAM-8f580740" there is for example the word "champions" that is not changing, then I can just get the content behind it by
$scope.champions = data.champions;
You were close:
$scope.teamName = 'TEAM-8f580740'; //or var teamName='TEAM-8f580740';
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
.success(function(data) {
$scope.champs = data[$scope.teamName];
});
If you want to get a value from a Javascript object, there are two options: using dot notation or bracket notation. Say you have this object:
var foo = {
"key": {"another_key": "baz"}
}
You can get the value using the dot notation:
foo.key
#returns {"another_key": "baz"}
If you don't know they name of the key until runtime, you can't use the dot, so you can use bracket notation to accomplish the same thing.
var key = "key"
foo[key]

Getting [object Object] in javascript when I want the value

I've looked at some similar questions, but not seeing exactly what I am doing wrong. I am passing a dict from a .py file to a file that uses javascript.
I know that the javascript file is getting my dict like this:
var numbersFromServer = [{"a": "45", "b": "22", "c": "7"}];
So, when I try something like this:
var numbersFromServer = {{ numbers_list|safe }};
var NumbersViewModel = function() {
var self = this;
theNumbers = [];
for (var key in numbersFromServer) {
theNumbers.push(numbersFromServer[key]);
}
self.num_display = ko.observableArray(theNumbers);
}
ko.applyBindings(new NumbersViewModel());
I am getting [object Object] when I want to get the actual values (45, 22, 7).
Can someone please point me in the right direction?
A fiddle that shows what I am trying to do: http://jsfiddle.net/Znk3q/1/
You have object in array so to get element you shoud
for (var key in numbersFromServer[0]) {
theNumbers.push(numbersFromServer[0][key]);
}
It looks like you have an array containing one object. To access it you need to
for (var key in numbersFromServer[0]) {
theNumbers.push(numbersFromServer[0][key]);
}

Categories

Resources