I can not display the default item in the select AngularJS - javascript

I'm trying to do that when I set the board, list should be updated , if it is empty it will show n / a if it does not display the number 0 in the list. But I have a problem such that when I set an board which has 4 lists. Then I will set the list to the last position, for example 4 and then I will set an array that does not have lists. I have not set default n / a, only in the drop-down list.
I tried set $scope.selectedList = '0'; And it works in case of changing boards where there are lists but not where they are not.
Please Help.
Here is the code:
template in controller
$scope.changeBoard = (_id) => {
var params = {
_id: _id
};
return ApiService.staff.selectedBoard(params).then((resp) => {
if (resp.lists.length === 0 || !resp.lists) {
$scope.downloadedLists.lists = [];
$scope.selectedList = '0';
} else {
$scope.downloadedLists = resp;
if (_id === $scope.board._id) {
$scope.selectedList = $scope.mainList;
$scope.selectedCard = $scope.mainCard;
} else {
$scope.selectedList = '0';
$scope.selectedCard = '0';
}
}
});
};
template html
<div class="transfer-btn">
<span>Tablica</span>
<span>{{board.name}}</span>
<select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
<option ng-repeat="item in boards" value="{{item._id}}">
{{item.name}}
</option>
</select>
</div>
<div class="transfer-btn">
<span>Lista{{selectedList}}</span>
<span>{{board.name}}</span> {{selectedListIn}}
<select class="form-control" name="" id="" ng-model="selectedList" ng-change="">
<option ng-repeat="item in downloadedLists.lists" value="{{$index}}">
{{item.list}}
</option>
<option value="0" ng-show="downloadedLists.lists.length == 0">n/a</option>
</select>
</div>

Do you have some of test data ?
It should good for you to test and debug if you will have a test data like following example. The following example design the test data to 5 sizes starting from 0 to 4. After that you should trial and see the result one by one.
What is the result when your input data is boardDataTest0 ?
What is the result when your input data is boardDataTest1 ?
What is the result when your input data is boardDataTest2 ?
What is the result when your input data is boardDataTest3 ?
What is the result when your input data is boardDataTest4 ?
Then it will help to give you some clue to test and debug in next step.
Test Data 0:
var boardDataTest0 = [];
Test Data 1:
var boardDataTest1 = [
{"id":1, "name": "board1", "description": "bla..bla..bla1" }
];
Test Data 2:
var boardDataTest2 = [
{"id":1, "name": "board1", "description": "bla..bla..bla1" },
{"id":2, "name": "board2", "description": "bla..bla..bla2" }
];
Test Data 3:
var boardDataTest3 = [
{"id":1, "name": "board1", "description": "bla..bla..bla1" },
{"id":2, "name": "board2", "description": "bla..bla..bla2" },
{"id":3, "name": "board3", "description": "bla..bla..bla3" }
];
Test Data 4:
var boardDataTest4 = [
{"id":1, "name": "board1", "description": "bla..bla..bla1" },
{"id":2, "name": "board2", "description": "bla..bla..bla2" },
{"id":3, "name": "board3", "description": "bla..bla..bla3" },
{"id":4, "name": "board4", "description": "bla..bla..bla4" }
];

Related

Is there a way to de-dupe a javascript array and combine values of the data?

I'm using an ajax request to grab some XML data which I then need to push into a chart in fusioncharts.
The XML data is formatted as [time taken], [work done], [which team done for], [who did it] (see below).
I'm iterating over the XML and then building the array using the code below:
//Time Recorded
if (columnidchecker == 7781) {
timearray.push($j(this).find('displayData').text());
temp1 = $j(this).find('displayData').text();
}
//Type of Activity
if (columnidchecker == 7782) {
activityarray.push($j(this).find('displayData').text());
temp2 = $j(this).find('displayData').text();
}
//Team Done For
if (columnidchecker == 7783) {
subjectarray.push($j(this).find('displayData').text());
temp3 = $j(this).find('displayData').text();
}
//Name
if (columnidchecker == 7777) {
internalclientarray.push($j(this).find('displayData').text());
temp4 = $j(this).find('userDisplayName').text();
}
});
//PUSH INTO A NEW ARRAY WHICH CAN THEN BE SORTED AND DE-DUPED WITH TIME COMBINED AGAINST ACTIVITY / TEAM.
objectarray.push([temp1, temp2, temp3, temp4]);
This builds an array of entries from the XML which basically outputs to something which looks like this:
0: (4) ["1.50", "Ad-hoc queries or calls", "Team 1", "James"]
1: (4) ["2.50", "Ad-hoc queries or calls", "Team 1", "James"]
2: (4) ["1.00", "Advice", "Team 2", "James"]
3: (4) ["3.50", "Meeting (External 3rd Party)", "Team 1", "James"]
4: (4) ["1.20", "Administration", Team 2", "James"]
5: (4) ["5.50", "Advice", "Team 1", "John"]
I'm trying to build a chart in fusioncharts which needs the format as shown below (ignore foot stuffs - it's taken straight from the fusioncharts help pages!).
{
"chart": {
"theme": "fusion",
"caption": "Revenue split by product category",
"subCaption": "For current year",
"xAxisname": "Quarter",
"yAxisName": "Revenues (In USD)",
"showSum": "1",
"numberPrefix": "$"
},
"categories": [
{
"category": [
{
"label": "Q1"
},
{
"label": "Q2"
},
{
"label": "Q3"
},
{
"label": "Q4"
}
]
}
],
"dataset": [
{
"seriesname": "Food Products",
"data": [
{
"value": "11000"
},
{
"value": "15000"
},
{
"value": "13500"
},
{
"value": "15000"
}
]
},
{
"seriesname": "Non-Food Products",
"data": [
{
"value": "11400"
},
{
"value": "14800"
},
{
"value": "8300"
},
{
"value": "11800"
}
]
}
]
}
The problem i'm having is that I cannot work out how to take the array of data with times, activity, team, name and push them into categories.
I think the first step is to create a new array of names which can be pushed into the "Category" data field in fusioncharts.
I then need a way in which to take the times being recorded against each activity and for each team and make sure it's assigned to the right person within the stacked bar chart and combine the amount of time spent. (i.e. "James" spent a total of 4 hours doing "Ad Hoc Queries and Calls" for Team 1 but this is split across two time entries so I need a way in which to combine them into one.)
Any help on this would be massively appreciated.
I can de-dupe the names to create a new array by using the following code:
namesarray.push(temp4);
uniq = [...new Set(namesarray)];
but after that it starts getting pretty complicated.
Maybe this can help you along the way. It's probably not exactly in the form you want it, but it demonstrates how you could break the problem down into smaller parts.
Pseudo-code:
get the unique names.
get the unique "task" names (for lack of a
better word)
for each unique person name:
3.1. get the data rows for that person
3.2 for each of all unique tasks names:
find the person data rows matching the task name
sum the duration of those data rows
const testData = [
[
"1.50",
"Ad-hoc queries or calls",
"Team 1",
"James"
],
[
"2.50",
"Ad-hoc queries or calls",
"Team 1",
"James"
],
[
"1.00",
"Advice",
"Team 2",
"James"
],
[
"3.50",
"Meeting (External 3rd Party)",
"Team 1",
"James"
],
[
"1.20",
"Administration",
"Team 2",
"James"
],
[
"5.50",
"Advice",
"Team 1",
"John"
]
];
const columnIndexByName = {
TASK_DURATION: 0,
TASK_NAME: 1,
FOR_WHICH_TEAM: 2,
PERSON_DOING_TASK: 3
};
const sum = (acc, next) => acc + next;
const uniqueNames = [...new Set(testData.map(row => row[columnIndexByName.PERSON_DOING_TASK])) ];
const uniqueTaskNames = [...new Set(testData.map(row => row[columnIndexByName.TASK_NAME])) ];
let result = {};
uniqueNames.forEach(personName => {
const personDataRows = testData.filter(row => row[columnIndexByName.PERSON_DOING_TASK] === personName);
let taskDurationsByTaskName = {};
uniqueTaskNames.forEach(taskName => {
const taskRows = personDataRows.filter(row => row[columnIndexByName.TASK_NAME] === taskName);
const taskDurations = taskRows.map(row => Number.parseFloat( row[columnIndexByName.TASK_DURATION] ));
const taskTotalDuration = taskDurations.reduce(sum, 0);
taskDurationsByTaskName[taskName] = taskTotalDuration;
})
result[personName] = taskDurationsByTaskName;
})
const renderData = data => document.querySelector("#output").innerHTML = JSON.stringify(data, null, 2);
renderData(result);
<pre id="output"></pre>

JS dynamically access & delete nested object property [duplicate]

This is the sample json:
{
"search": {
"facets": {
"author": [
],
"language": [
{
"value": "nep",
"count": 3
},
{
"value": "urd",
"count": 1
}
],
"source": [
{
"value": "West Bengal State Council of Vocational Education & Training",
"count": 175
}
],
"type": [
{
"value": "text",
"count": 175
}
],
}
}
There are several ways to delete key search.facets.source:
delete search.facets.source
delete jsobObj['search']['facets']['source']
var jsonKey = 'source';
JSON.parse(angular.toJson(jsonObj), function (key, value) {
if (key != jsonKey)
return value;
});
Above 1 & 2 are not dynamic, and 3 is one of the way but not a proper way. Because if source is present in another node then it will not work. Please anybody can tell me how to delete it dynamically in any kind of nested key. Because we can not generate sequence of array dynamically in above 2.
Assuming you're starting from this:
let path = 'search.facets.source';
Then the logic is simple: find the search.facets object, then delete obj['source'] on it.
Step one, divide the path into the initial path and trailing property name:
let keys = path.split('.');
let prop = keys.pop();
Find the facets object in your object:
let parent = keys.reduce((obj, key) => obj[key], jsonObj);
Delete the property:
delete parent[prop];
I have found out another solution, it is very easy.
var jsonKey = 'search.facets.source';
eval('delete jsonObj.' + jsonKey + ';');

Firebase ordering and retrieving the index for a specific record

I'm using Firebase 2.4.2. I have a database as follows:
"items": {
"item1": {
"details": {
"name": "item 1",
"rate": 5
},
"item2": {
"details": {
"name": "item 2",
"rate": "4"
}
}
"item3": {
"details": {
"name": "item 3",
"rate": "6"
}
}
}
I have thousands of items and don't want to load them all in a table. Rather, I'd like to load the top10 along with the item that user has clicked on. So, if you are in the page: /items/details/item2, I'd like you see the top10 items in the database (based on their rates) and the item2 in a table. I'd also like to show the index of item2 in the ordered list.
ind id rate
1 item56 100
2 item33 98
...
143 item2 13
What we do normally -if the bandwidth is not issue- is to retrieve all data as follows (e.g. using AngularFire)
var ref = fbutil.ref('items').orderByChild('details/rate');
return $firebaseArray(ref);
However, I'd like to order them, retrieve the top10, and then retrieve the item2 (in this case) and its index (143) based on its rate.
How would I do that?
// For getting top 10
var ref = fbutil.ref('items').orderByChild('details/rate').limitToFirst(10);
return $firebaseArray(ref);
// For getting single
var ref = fbutil.ref('items').orderByChild('details/rate').equalTo(13);
var singleItem = $firebaseObject(ref);
Checkout the following link to see what methods firebase.database.Reference class supports.
https://firebase.google.com/docs/reference/js/firebase.database.Reference

Splice from ng-options in select drop downusing filter

How can I splice some elements in an array to display it in ng options
Heres the JSON
$scope.result=[
{
"id": 1,
"name": "min",
},
{
"id": 2,
"name": "hour",
},
{
"id": 3,
"name": "second",
},
{
"id": 4,
"name": "inch",
},
{
"id": 5,
"name": "km",
}
]
I want to splice inch and km from the array and display it it select dropdown
<select ng-options="r.id as r.name for r in result"><option value="">--Select---</option></select>
Have also tries inline filter that will only display based on id's like tihis <select ng-options="r.id as r.name for r in result|filter:{id:'!4'}"><option value="">--Select---</option>
</select>
But this will splice only one element ie.,with id:5(km).I want to splice id:4 as well
Use native javascript filter for your work
var newResult = $scope.result.filter(function(obj){
return obj.name === 'km' || obj.name === 'inch';
});
console.log(newResult); // will give expected result.
You can assign the result of filter to the key in scope on which you want to loop.

Populate a variable using jQuery based on selections in a drop down

I'm trying to build a nested array in jQuery based on a user's selection from a drop down menu. This will be used in a JSON request at a later date.
So far my code does produce (almost) the required result, however no matter order i select the options from my drop down menu, the output (which i log in the console at the end) is always the same.
$('#comboGenre').change(function () {
var values = $('#comboGenre').val();
var parsedJSON = JSON.parse($data); //Data returned from ajax request
for (var i = 0; i < values.length; i += 1) {
$genreList = parsedJSON.genre[i];
console.log($genreList);
}
});
So if i select RPG and Action from my drop down, the output gives me RPG and Driving. If i selected RPG, Driving and Action (in that order), i get what i would expect RPG, Driving and Action.
So it's just iterating through my JSON, when really it should be returning the 'selected' option.
How can i achieve this?
My JSON looks like this if it's useful:
{"genres": [{
"genre": "RPG",
"publishers": [{
"publisher": "Square",
"games": [{
"game": "FFX",
"rating": [
12, 15
]
}]
}]
},
{
"genre": "Driving",
"publishers": [{
"publisher": "Turn10",
"games": [{
"game": "Forza",
"rating": [
5
]
}]
}]
},
{
"genre": "Action",
"publishers": [{
"publisher": "EA",
"games": [{
"game": "COD",
"rating": [
18, 20
]
}]
}]
}
]}
EDIT:
I've also tried this:
$('#comboGenre').change(function () {
var parsedJSON = JSON.parse($data);
$genreList = "";
$.each(parsedJSON.genres, function(index, value){
$genreList = parsedJSON.genres[index];
console.log($genreList);
});
});
And i end up getting ALL the objects in my JSON, so from here, i'm only wanting to add the selected object to the $genreList variable.
If you broke out some of the logic and created a genre finding function and used the selected string to find the proper object you could then put the object into the variable you will use later. I do some checking to ensure that the genre that has been selected isn't already in my array which is because I am using the multiple select
JSFiddle: http://jsfiddle.net/vkTFq/
Code:
$(function(){
var selectedGenres = [];
var genres =[{"genre":"RPG","publishers":[{"publisher":"Square","games":[{"game":"FFX","rating":[12,15]}]}]},{"genre":"Driving","publishers":[{"publisher":"Turn10","games":[{"game":"Forza","rating":[5]}]}]},{"genre":"Action","publishers":[{"publisher":"EA","games":[{"game":"COD","rating":[18,20]}]}]}]
$('#comboGenre').change(function() {
$(this).find(":selected").each(function() {
var selectedGenre = findGenre($(this).val())
if (!genreAlreadySelected(selectedGenre.genre)) {
selectedGenres.push(selectedGenre);
};
});
console.log (JSON.stringify(selectedGenres));
});
function genreAlreadySelected(genre){
for(var i = 0; i < selectedGenres.length; i++){
if (genre == selectedGenres[i].genre) {
return true;
};
return false;
}
}
function findGenre(genre){
for(var i = 0; i < genres.length; i ++){
console.log(genre)
if(genre == genres[i].genre){
return genres[i];
}
}
};
});

Categories

Resources