Angularjs add new field in for loop error - javascript

I am trying to add a new "field" ( not sure if it's called as field ) in an array,
but it stops at a certain number. For example, I have 33 objects in the array, it stops at the 7th object.
My JS:
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
$scope.community[i].visibility = true;
console.log($scope.community[i])
}
The error it throws me
PS: Visibility doesn't exist in my object, I am adding it in
More info :
When i console log the whole array it returns me with 33 object
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
console.log($scope.community)
}
But when i console log it with the [i] loop
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
console.log($scope.community[i]) <----
}
I get 6 returns with 27 undefined returns ..

Some of the Objects does not have a property named visiblility , you should be able to handle with the following code,
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
if($scope.community && $scope.community[i]){
$scope.community[i].visibility = true;
console.log($scope.community[i])
}
}

Related

Skipping undefined elements from an API call

I am gathering data from an API to show the Pokemon typing. Some Pokemon have one type, while others have two.
The variables to gather the typing data are as such.
function createPokemonCard(pokemon) {
const type = pokemon.types[0].type.name;
const second_type = pokemon.types[1].type.name;
...}
And then I call them via InnerHTML in the same function with the following code.
<small class="type"><span>${type}/${second_type}</span></small>
Predictably, when it hits undefined for a Pokemon, it breaks and doesn't display the card. However I am not sure how to get it to not print the second type when it's undefined.
I thought about doing an if statement, but what should I call if there is an undefined variable?
function undefined {
if(second_type === 'undefined') {
???
}}
Or would a for loop work better? I am not sure how to get it to bypass the undefined and print nothing.
const second_type = pokemon.types[1] ? pokemon.types[1].type.name: undefined;
`<small class="type"><span>${type}${second_type!=undefined ? `/${second_type}`: ''}</span></small>`
The ? : syntax is a ternary operator (mdn)
It's a less verbose way of writing out the following:
if (second_type!=undefined) { // check if second_type is not undefined
return `/${second_type}` // if it's not return / and the second type
} else { //otherwise
return '' // return an empty string
}
If you do not want to display the trailing / when second_type is not defined one way to go could be
const type = pokemon.types.map(({ type }) => type.name).join("/")
and then
<small class="type"><span>${type}</span></small>

How can I get the length of a computed array in Vue.js

I have a search input that searches through a JSON file - it works fine, I am now trying to display the number of results found to the user. (eg. '26 results found' - or 'No results found')
I am using a computed method that checks if the user has clicked on the search input, and then checks through the JSON file to match the user's query to a string in the JSON file. This is my current code:
computed: {
filteredPrizesByQuery: function() {
if (this.searchInputClicked == true) {
return this.prizes.filter(prize => {
return (
prize.prizeTitle.toLowerCase().match(this.query) ||
prize.prizeTag.toLowerCase().match(this.query)
)
});
} else
return this.prizes.filter(prize => {
return (
prize.prizeType1Name.match(this.tabbedQuery) ||
prize.prizeType2Name.match(this.tabbedQuery)
);
});
}
}
When I type in a query in the search box and then look at my Vue Dev Tools, I can see the Array count is updated (under computed) eg. filteredPrizesByQuery:Array[26]. This is the value I want to display to the user, but I can't figure out how to access this value.
I have tried checking the length of filteredPrizesByQuery or the length of 'prize' within the computed method, but I either get a maximum call stack size error or undefined.
You can simply create another computed property and access the filteredPrizesByQuery computed property length there like:
computed: {
filteredPrizesByQuery: function() {
// Your current logic returning array here...
},
filteredPrizesCount: function() {
return this.filteredPrizesByQuery.length;
}
}
and then update UI like:
<p>{{filteredPrizesCount}} results found</p>

Comparing problem with If else statement in Javascript

I have two condition of my same JSON data:
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[
{
"letterNo":13,
"letterId":1,
"inout":"out",
"inoutNo":"12332466544",
"inoutDate":"2070-01-01",
"letterIssuedSubBy":null,
"letterFile":null,
"representativeName":null,
"representativeNameEng":null,
"selectionId":124,
"assessmentNo":null,
"entryBy":"user98",
"rStatus":"I",
"others":null,
"signatary":"qwerrt",
"letterBox":null,
"imageFile":null,
"imageTitle":null,
"reminderYesNo":"N"
}
]
}
Same JSON with letter array empty structure :
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[]
}
All these values are stored in
var trDataSecondTable; . I tried to compare if the letter is empty or not by using if condition:
if(trDataSecondTable.letter != null) {
console.log("asasfasdfdsfdsfds");
$("#inoutDate").val(trDataSecondTable.letter[0].inoutDate);
$("#inoutNo").val(trDataSecondTable.letter[0].inoutNo);
$("#signatary").val(trDataSecondTable.letter[0].signatary);
}
else
{
console.log("entered in else part");
}
Though "letter":[] is empty it is not entering into else part. While comparing i also tried trDataSecondTable.letter.length != 0 but also it is not entering into else part.
Your condition should check for both null and the length:
if (trDataSecondTable.letter != null && trDataSecondTable.letter.length > 0)
Is is important to check for null before accessing the length property as it guarantees you won't try to access the length property on null, which would raise an exception. This is important since data is rarely reliable.
Because of the && operator, if the first check fails, the second check won't be evaluated.
Actually, an even safer way would be to check if the value is truthy, as this will work for null and undefined:
if (trDataSecondTable.letter && trDataSecondTable.letter.length > 0)
You could check the length of the array.
if (trDataSecondTable.letter.length) {
// letter has some elements
} else {
// no elements
}
I think this condition is enough
if(trDataSecondTable.letter.length)

Using Filter Function to Find Values Equal to False and Setting to True

In my Angular app I have a function that drills down to an array, and then uses a filter function to pull out values in a new array where "completed" is "false".
This is working as expected. And the way our data is, there is always one object in the array that has the property for "completed" set to "false", so I can target [0] to get to that. So, from there all I need to do is set it to "true". However, for whatever reason, how to accomplish this last step is eluding me.
This is my whole function, and what I've tried thus far:
private completeLastWorkflowStatus() {
let currentService = this.checkDiscipline();
for (let service of this.client.services) {
if (service.service === currentService) {
let targetWorkflow = service.workflow;
let inCompleteWorkflow = targetWorkflow.filter(workflow => workflow.completed === false);
console.log(inCompleteWorkflow);
if (inCompleteWorkflow[0].completed === false) {
inCompleteWorkflow[0].completed === true;
console.log(inCompleteWorkflow[0].completed);
}
}
}
}
For the last console.log listed above, I still get "false" as the value. What am I missing here? How can I set the value of "completed" to "true" for this one object in the array?
inCompleteWorkflow[0].completed === true; is not assignment. Do inCompleteWorkflow[0].completed = true;

catch null object in js

How can i catch the object is null or not an object. Actually i have wrote this line in if condition for solving it, but not working.
But Generating ERROR :- "object is null or not an object"
var preWynum = "";
function paint(Wynum)
{
// alert("Wynum:"+Wynum +", preWynum:"+preWynum);
if(document.getElementById(preWynum) && document.getElementById(Wynum))
{
document.getElementById(preWynum).style.backgroundColor='white';
document.getElementById(Wynum).style.backgroundColor='yellow';
}
preWynum = Wynum;
}
I dont believe why it not running.
Any other idea ?
preWynum and Wynum is the id of tr(table row).
I want to set background color with yellow to current selected row(that's id is Wynum).
The error is because you are passing an object (non-existent) to getElementById() when it expects a string:
// Put quotes around 'preWynum' and 'Wynum'
if(document.getElementById('preWynum') && document.getElementById('Wynum'))
{
document.getElementById('preWynum').style.backgroundColor='white';
document.getElementById('Wynum').style.backgroundColor='yellow';
}

Categories