Below is the data i get from the rest API
{
"memberdetails":[
{
"id":46,
"customername":"Zack",
"phoneno":"1323223232",
"nickname":"Zack",
"regdate":"2017-12-27 18:38:36.185829",
"groupname":"Test group",
"regid":36,
"groupdesc":"Test Test test",
"groupicon":"new",
"tamount":"3100"
},
{
"id":46,
"customername":"Carol",
"phoneno":"254721493487",
"nickname":"Caro",
"regdate":"2017-12-28 23:47:22.317687",
"groupname":"Test",
"regid":36,
"groupdesc":"Test Test Test",
"groupicon":"new",
"tamount":"130"
}
]
}
From the above data i want to populate 2 arrays as i want to plot a graph in the below format. The lineChartData array should pick the tamount and the lineChartLabels Array should pick the customenames. Thank you.
public lineChartData:Array<any> = [{data: [15, 29, 24, 21, 26, 15, 10], label: 'Opening/Time'}];
public lineChartLabels:Array<any> = ["Dan","Were","Kibe","Zack","Evah","Chris","Jess"];
angular.module('testapp', [])
.controller('TestCtrl', function(){
this.inputData = {
"memberdetails": [
{
"id": 46,
"customername": "Zack ",
"phoneno": "1323223232",
"nickname": "Zack ",
"regdate": "2017-12-27 18:38:36.185829",
"groupname": "Test group ",
"regid": 36,
"groupdesc": "Test Test test ",
"groupicon": "new ",
"tamount": "3100"
},
{
"id": 46,
"customername": "Carol ",
"phoneno": "254721493487",
"nickname": "Caro ",
"regdate": "2017-12-28 23:47:22.317687",
"groupname": "Test ",
"regid": 36,
"groupdesc": "Test Test Test ",
"groupicon": "new ",
"tamount": "130"
}
]
};
this.expectedOutput = {
"lineChartData": [
{
"data": [
15,
29,
24,
21,
26,
15,
10
],
"label": "Opening\/Time"
}
],
"lineChartLabels": [
"Dan",
"Were",
"Kibe",
"Zack",
"Evah",
"Chris",
"Jess"
]
}
this.computedLineChartData = [{data:[],label:"Opening\/Time"}];
this.computedLineChartLabels = [];
for(var i=0;i<this.inputData.memberdetails.length; i++){
var curMember = this.inputData.memberdetails[i];
this.computedLineChartData[0].data.push(curMember.tamount);
this.computedLineChartLabels.push(curMember.customername);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="testapp" ng-controller="TestCtrl as tc">
<pre>{{tc|json}}</pre>
</div>
In AngularJs we have function like angular.fromJson(data) which returns output in form of array . So you can easily convert json to array.
Related
I have fetched data from a JSON file.. But when I tried to fetch another data from it, am unable to do so as it is a nested array... I know the solution can arrive easily but this is the first time am trying to loop a JSON file.. so kindly give your inputs.
SampleData = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Immortality",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
};
GetJsonData() {
console.log(this.SampleData["powers"]);
for (let i = 0; i < this.SampleData["powers"].length; i++) {
if (this.SampleData["powers"][i].Immortality) {
console.log(this.SampleData.powers[i]);
}
}
}
{name: "Molecule Man", age: 29, secretIdentity: "Dan Jukes", powers: Array(3)}
{name: "Eternal Flame", age: 1000, secretIdentity: "Unknown", powers: Array(3)}
Your code needs to follow the structure of the JSON data; in particular, these are all valid things you could print:
console.log(this.SampleData.squadName);
console.log(this.SampleData.homeTown);
console.log(this.SampleData.members[0].name);
console.log(this.SampleData.members[0].powers[0]);
If you wanted to loop through each member and print their info, that might look like this:
this.SampleData.members.forEach(member => {
let powerString = member.powers.join(', ');
console.log('Name: ' + member.name);
console.log('Age: ' + member.age);
console.log('Powers: ' + powerString);
});
I used a forEach, but you can also use a for (let i = loop.
I created a local version of this example.
This example works both with Angular 1.3 and 1.5 in a Codepen.
But there's an error in a console in a local version.
The code is the same:
angular.module("winnieApp", []);
angular.module("winnieApp").controller("winnieCtrl", ['$scope',
'$filter', function($scope, $filter){
$scope.friendsArr = [{"id": 1, "name":"Winnie", "age": 76, "food": "hunny"},
{"id": 2, "name":"Piglet", "age": 43, "food": "grains"},
{"id": 3, "name":"Tigger", "age": 52, "food": "meat"},
{"id": 4, "name":"Rabbit", "age": 34, "food": "carrot"},
{"id": 5, "name":"Eeyore", "age": 63, "food": "grass"}];
$scope.search = {
setFilter: function(method){ $scope.search.currentFilter =
$scope.search[method]; },
allage: function(data){ return true; },
ageLow: function(data){ return data.age < 50; },
ageHeight: function(data){ return data.age >= 50; },
};
}]);
Solved. There was 'ng-app="countryApp"' in my HTML tag.
Hi can somebody help Removing element from nested json array like this
JSON
[{
"id": 1,
"name": "Furniture & Fixture",
"choice": {
"0": {
"req_goods": "table",
"qty": "10"
},
"1": {
"req_goods": "chair",
"qty": "5"
}
}
}, {
"id": 2,
"name": "Miscellaneous Property",
"choice": {
"0": {
"req_goods": "Office Rent",
"qty": "1"
}
}
}]
here how do I remove choice 1 of id 1 .
HTML
<div ng-repeat="cb in capital_budgets">
<div ng-repeat="choice in choices[$index]">
<input ng-model="cb.choice[$index].req_goods">
<input ng-model="cb.choice[$index].qty">
<button ng-hide="$first" ng-click="removeChoice($parent.$index,$index)">-</button>
</div>
<button ng-click="addNewChoice($index)">+</button>
</div>
JS
$scope.capital_budgets = [{"id":1,"name":"Furniture & Fixture"},
{"id":2,"name":"Miscellaneous Property"}];
$scope.choices = [{}];
$scope.choices[0] = [{}];
$scope.choices[1] = [{}];
$scope.choices[2] = [{}];
$scope.choices[3] = [{}];
$scope.choices[4] = [{}];
$scope.addNewChoice = function(id) {
$scope.choices[id].push({});
};
$scope.removeChoice = function(parent_id, id) {
$scope.choices[parent_id].splice(id, 1);
};
The Above removeChoice() remove last element but I want to remove the element that user choose to remove. please help i have been trying from 2 days.
You can make 'choice' of the array type as follows and use the index of the particular choice in the ng-repeat directive to remove the choice from the choices array.
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
vm.removeChoice = removeChoice;
vm.addChoice = addChoice;
function removeChoice(itemId, index) {
for (var i = 0; i < vm.items.length; i++) {
if (vm.items[i].id === itemId) {
vm.items[i].choices.splice(index, 1);
break;
}
}
}
function addChoice(index) {
var id = vm.items[index].choices.length + 1;
vm.items[index].choices.push({
id: id,
req_goods: "",
qty: 0
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<div ng-repeat="item in ctrl.items">
<h3>{{item.name}}</h3>
<div ng-repeat="choice in item.choices">
<input type="text" ng-model="choice.req_goods" />
<input type="text" ng-model="choice.qty" />
<button type="button" ng-click="ctrl.removeChoice(item.id, $index)">Remove</button>
</div>
<button type="button" ng-click="ctrl.addChoice($index)">Add</button>
</div>
</div>
</div>
You can remove choice "1" of id 1 using the below code snippet.
var json = [
{
"id": 1,
"name": "Furniture & Fixture",
"choice": {
"0": {
"req_goods": "table",
"qty": "10"
},
"1": {
"req_goods": "chair",
"qty": "5"
}
}
}, {
"id": 2,
"name": "Miscellaneous Property",
"choice": {
"0": {
"req_goods": "Office Rent",
"qty": "1"
}
}
}];
function removeChoice(json, parentId, choice) {
for (var i = 0; i < json.length; i++) {
if (json[i].id === parentId) {
delete json[i].choice[choice];
break;
}
}
}
removeChoice(json, 1, "1");
console.log(json);
If you want the the choice also to be of the same type as its parent element i.e. an array you could change your JSON as follows and do as shown in the below code snippet to remove a choice from the JSON
var json = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
function removeChoice(json, parentId, choiceId) {
for (var i = 0; i < json.length; i++) {
if (json[i].id === parentId) {
for (var j = 0; j < json[i].choices.length; j++) {
if (json[i].choices[j].id === choiceId) {
json[i].choices.splice(j, 1);
break;
}
}
break;
}
}
}
removeChoice(json, 1, 1);
console.log(json);
In both of the above methods I've passed the source you want to modify as a parameter to the removeChoice function whereas you can also directly use a variable available within the scope of execution of the removeChoice function and pass only parentId and choiceId as parameters in the below code snippet, you can replace items with the object on your controller's $scope.If you prefer isolation of the code you can pass the items object as a parameter to the removeChoice function as it won't be dependent on the external components directly being used in the method body, I would suggest to have separation of concerns.
var items = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
function removeChoice(parentId, choiceId) {
for (var i = 0; i < items.length; i++) {
if (items[i].id === parentId) {
for (var j = 0; j < items[i].choices.length; j++) {
if (items[i].choices[j].id === choiceId) {
items[i].choices.splice(j, 1);
break;
}
}
break;
}
}
}
removeChoice(1, 1);
console.log(items);
Try This
$scope.removeChoice = function(parent_id,id) {
var TempArr=[];
var parentLength=$scope.choices[parent_id].length;
for(i=0;i<parentLength;i++ ){
if(parentLength[i]!==id){
TempArr.push(parentLength[i]);
}
if(i==parentLength-1){
$scope.choices[parent_id]=[];
$scope.choices[parent_id]=TempArr;
}
}
};
I need to sort my json array in chronological order by it's created_at timestamps.
[{
"id": 1,
"message": "hello",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:34",
"updated_at": "2015-07-01 12:56:34"
}, {
"id": 2,
"message": "helloWorld",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:53",
"updated_at": "2015-07-01 12:56:53"
}, {
"id": 3,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:12:53",
"updated_at": "2015-07-01 13:12:53"
}, {
"id": 4,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:13:04",
"updated_at": "2015-07-01 13:13:04"
}, {
"id": 5,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 15:06:39",
"updated_at": "2015-07-01 15:06:39"
}, {
"id": 1,
"message": "yo yo ",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 22:09:36",
"updated_at": "-0001-11-30 00:00:00"
}, {
"id": 2,
"message": "sup nigga",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 14:00:00",
"updated_at": "-0001-11-30 00:00:00"
}]
Can anyone teach me how do i have tried many solutions in stackoverflow . Many of them says array cannot be used with "sortBy" .
This is part of my code :
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
$message = array();
if($companyMessage->count()>0 || $investorMessage->count() > 0){
if($lastActivityDate == null ){
//load all messages before
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
return $message ;
}
I think you can do this using use a laravel database collection api instead of array and add item to collection and use sortBy method on collection,
$col = new \Illuminate\Database\Eloquent\Collection();
if ($companyMessage != null) {
foreach($companyMessage - > get() as $cm) {
$col->add($cm);
}
}
if ($investorMessage != null) {
foreach($investorMessage - > get() as $im) {
$col->add($im);
}
}
$col = $col->sortBy('created_at');
//return the json
return Response::json($jsonArr->toArray());
--- OR ----
Try this but i didn't tested it. If this works then this would be the best way to do this.
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
//$companyMessage & $investorMessage both are laravel database collection,
// so you can use merge method on collection to merge these two collections.
$allResults = $companyMessage->merge($investorMessage);
//use laravel collection sort method to sort the collection by created_at
$allResults = $allResults->sortBy('created_at');
//return the json
return Response::json($allResults->toArray());
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
$message = array_values(array_sort($message, function ($value) {
return $value['created_at'];
}));
Hey man , i found a better solution to sort my array. The answer can be found at laravel docs
http://laravel.com/docs/5.1/helpers#method-array-sort
I have this json which populates my collection (TableListCollection) of models (TableModel)
{
"tables": [
{
"tableId": 15,
"size": 8,
"occupiedSeats": 0,
"stakes": {
"smallBlindAmount": 10,
"bigBlindAmount": 20,
"minBuyInAmount": 20,
"maxBuyInAmount": 200
},
"gameType": "HOLDEM",
"gameSpeed": "NORMAL",
"friends": []
},
{
"tableId": 16,
"size": 8,
"occupiedSeats": 0,
"stakes": {
"smallBlindAmount": 20,
"bigBlindAmount": 40,
"minBuyInAmount": 20,
"maxBuyInAmount": 200
},
"gameType": "HOLDEM",
"gameSpeed": "NORMAL",
"friends": []
},
{
"tableId": 17,
"size": 8,
"occupiedSeats": 0,
"stakes": {
"smallBlindAmount": 40,
"bigBlindAmount": 60,
"minBuyInAmount": 20,
"maxBuyInAmount": 200
},
"gameType": "HOLDEM",
"gameSpeed": "NORMAL",
"friends": []
}
]
}
I want to find the table with the minimum smallBlindAmount.
I see that I can use the _.min() but I can't figure out what I have to pass as an iterator.
Thanks in advance.
Either directly on the JSON
var json=...
var min = _.min(json.tables,function(item) {
return item.stakes.smallBlindAmount
});
console.log(min.stakes.smallBlindAmount);
or on your collection
var json=...
var c=new Backbone.Collection(json.tables);
var m=c.min(function(model) {
return model.get("stakes").smallBlindAmount
});
console.log(m.get("stakes").smallBlindAmount);
In both cases, the iterator is used to extract the values to be compared.