Calculating with JSON array data - javascript

Stuck once again today, but i am trying to calculate with specific values from a JSON array. I can't seem to isolate the appropriate data. Can someone help me with this?
This is my JSON response:
[{"employee":[{"firstname":"Harry","birthdate":"1965-10-05","age":50}]},{"employee":[{"firstname":"Pete","birthdate":"1985-10-09","age":30}]}]
I'd like to get all the ages and add them for further use (for example average age). Help would be appreciated :)

Here is a working example for you:
var jsonData = [{"employee":[{"firstname":"Harry","birthdate":"1965-10-05","age":50}]},{"employee":[{"firstname":"Pete","birthdate":"1985-10-09","age":30}]}];
var sumOfAges = 0;
for(var i = 0; i<jsonData.length; i++){
sumOfAges += jsonData[i]["employee"][0].age;
}
console.log(sumOfAges);
var averageAge = sumOfAges / jsonData.length;
console.log(averageAge);
you can find the fiddle here:
http://jsfiddle.net/La9rzh8t/1/

Using Array#reduce and JSON#parse we can quite easily sum all ages of each employee in your data.
Here is a JSFiddle which uses the below function:
function sumAllAges(data) {
return data.reduce(function(total, obj) {
total += obj.employee[0].age;
return total;
}, 0);
}

Related

How to calculate the P/E ratio of the stocks?

Formula to calculate is, Portfolio P/E = Net Worth/Sum(Stock EPS * Shares Held)
I have the value for net Worth but I am unable to iterate over the EPS values and multiply it by the shares held. Can you please suggest some solution for this. Thank you!
Here is the plunker
<div>
<h3>P/E Ratio: {{getNetWorth())}}
</div>
Script:
$http.get('data.json').then(function(response) {
$scope.stocksArray = [];
var indexes = [];
var epsindex = [];
var eps = {};
$scope.eps = response.data.eps;
It won't win any awards, but here is the long and short of the problem.
Your json file is structured oddly like this:
-price
--stock-name:stock-price
-eps
--stock-name:stock-eps
It should be structure like this:
-stock-name
--price:actual-price
--eps:actual-eps
This would let you pull it in as objects without needing to instantiate the entire collection manually. But I played with the data I was given and it works.
The key is the following two line
$scope.eps = response.data.eps;
AND
mystock.eps = $scope.eps[key];
By adding the eps collection as a seperate array I was able to add it as a field in the object property.
getPortfolioPE() was the easy part:
$scope.getPortfolioPE = function(){
let temp = 0;
let total = 0;
for(let i = 0; i < $scope.stocksArray.length; i++){
total += $scope.stocksArray[i].eps * $scope.stocksArray[i].shares
}
temp += $scope.getNetWorth()/ total;
return temp.toFixed(2);
}
I think your $http.get should return an array of stocks, and the PE ratio is a property of each array element.
Therefore, you should have something like this in controller:
$scope.stocks = response.data;
And you may need use ng-repeat in template, something like this:
<li ng-repeat="item in stocks">
You PE is: {{item.pe}}
</li>

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

parsing a json in loop where element names change

I'm parsing a JSON response which isn't set up the best, in my opinion. Here is the actual response:
[
{"challenge_id":"39029"},
{"song1_id":"198","name":"PRAY","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/TAKE_THAT_-_PRAY.mp3"},
{"song2_id":"251","name":"THE TEARS OF A CLOWN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/SMOKEY_ROBINSON_-_THE_TEARS_OF_A_CLOWN.mp3"},
{"song3_id":"11","name":"WONDERFUL TONIGHT","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ERIC_CLAPTON_-_WONDERFUL_TONIGHT.mp3"},
{"song4_id":"288","name":"THE NAME OF THE GAME","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ABBA_-_THE_NAME_OF_THE_GAME.mp3"},
{"song5_id":"159","name":"I'M EVERY WOMAN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/CHAKA_KHAN_-_I'M_EVERY_WOMAN.mp3"},
{"status":"ok"}
]
and here was my attempt at parsing it:
var challenge_Songs = JSON.parse(this.responseText);
for(var i = 1; i<challenge_Songs.length-1; i++){
challengeSongs[i-1] = challenge_Songs[i].url;
challengeTitles[i-1] = challenge_Songs[i].name;
voteSongIds[i-1]= challenge_Songs.song[i]_id;
}
My problem is with obtaining what I have set up as voteSongIds, as the name changes within every iteration of the loop. What I have tried above is causing a run time error. If I comment the line with votesongids, everything works. How should I parse the parse JSON?! Any help appreciated :) I'm using titanium, but for these purposes, it's just javascript!
Is this the result you looking for?
var challenge_Songs = [
{"challenge_id":"39029"},
{"song1_id":"198","name":"PRAY","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/TAKE_THAT_-_PRAY.mp3"},
{"song2_id":"251","name":"THE TEARS OF A CLOWN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/SMOKEY_ROBINSON_-_THE_TEARS_OF_A_CLOWN.mp3"},{"song3_id":"11","name":"WONDERFUL TONIGHT","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ERIC_CLAPTON_-_WONDERFUL_TONIGHT.mp3"},
{"song4_id":"288","name":"THE NAME OF THE GAME","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ABBA_-_THE_NAME_OF_THE_GAME.mp3"},
{"song5_id":"159","name":"I'M EVERY WOMAN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/CHAKA_KHAN_-_I'M_EVERY_WOMAN.mp3"},{"status":"ok"}]
var challengeTitles=[],
challengeSongs = [],
voteSongIds=[];
for(var i = 1; i < challenge_Songs.length-1; i++){
challengeTitles.push(challenge_Songs[i]['name']);
challengeSongs.push(challenge_Songs[i]['url']);
voteSongIds.push(challenge_Songs[i]['song'+ i +'_id'])
}
console.log(challengeTitles);
console.log(challengeSongs);
console.log(voteSongIds);
Try the following code. This will work perfect whatever the key or value
for(var i = 0; i<challenge_Songs.length; i++){
for(key in challenge_Songs[i]){
console.log("\n key=>" + key + " : value=> " + challenge_Songs[i][key]);
}
console.log("\n");
}
It will display you all the keys and correspondent value in more simple way

Looping through nested arrays in Javascript

So I have an API that returns JSON data
Example JSON:
{
"result":"OK",
"data":[
{
"number":"613-555-5555",
"calls":30
},
{
"number":"613-666-5555",
"calls":100
}
]
}
I am trying to output this using javascript to show the following
[number, calls],[number, calls]
var response = response.data;
var length = response.length;
alert(data[0].number);
alert(data[0].calls);
for (var i = 0; i < data.length; i++) {
var arrayItem = data[i];
document.write(arrayItem);
}
This is simply a question of mapping your data to the desired format:
var final = response.data.map(function(item) {
return [item.number, item.calls];
});
console.log(final);
Here is a demo: http://jsfiddle.net/c8UQg/
EDIT:
I didn't realise you were looking for a string representation (I thought you wanted an array). If that is the case, please disregard the above.
If you like everything the way it is code wise, and just want to fix the error, then I suggest changing
var response = response.data;
to
var data = response.data;
Also, for the sake of debugging, change
document.write(arrayItem);
to
console.log(arrayItem);
http://jsfiddle.net/GptRW/

MVC: Iterating a Viewbag array in javascript

The goal is to get the data from the ViewBag.Array to a Javascript array. The data is calculated in the controller so I cannot fetch it straight from the database. I need the data to draw a chart with jqplot. Code:
for(i = 0; i < #ViewBag.Array.Length; i++)
{
jScriptArray[i] = #ViewBag.Array[i];
}
The problem is "'i' does not exist in the current context" in the #ViewBag.Array[i] but has no problems in the jScriptArray[i]. Any help is appreciated.
You may try the following:
var array = #Html.Raw(Json.Encode(#ViewBag.Array));
for(var i = 0; i < array.length; i++) {
jScriptArray[i] = array[i];
}
var array=#Html.Raw(JsonConvert.SerializeObject(ViewBag.Array));
you can make use of JsonConvert.SerializeObject
Hope this Helps.
<script>
var jScriptArray=[];
#{
for(i = 0; i < ViewBag.Array.Length; i++){
<text>jScriptArray[#i] = "#ViewBag.Array[#i]";</text>
i++;
}
}
</script>
You will end up with something like this in html file:
jScriptArray[0] = "ArrayValue0";
jScriptArray[1] = "ArrayValue1";
jScriptArray[2] = "ArrayValue2";
The best way to achieve your goal is to create a JSON controller that returns the data into a JSON array.
From your javascript you can request the data and then process it.
Hope this helps

Categories

Resources