Replace value with API value in ng-repeat - javascript

I am listing a bunch of JSON objects to a view, but only it's category ID is included. Not the name, which I need to display. I have to make a separate $http call to process which items match. Values will not render to view. Code:
$scope.cardCategories = function(id) {
angular.forEach($scope.categoryFilter, function(category, index){
if (category.id == id) {
//console.log(category.name);
return category.name;
} else {
return;
}
})
}
value inside a simplified ng-repeat
<div ng-repeat="topic in latest">
{{cardCategories(topic.category_id)}}
</div>
I have also attempted to write this as a filter, but the value will not display. Console shows the matches. My suspicion is that I have to process the original latest array. Thanks.
.filter('cardCategories', function($rootScope, $state){
return function(catId) {
if (catId !== undefined && $rootScope.cardCategories) {
angular.forEach($rootScope.cardCategories.categories, function(category, index){
if (category.id == catId.category_id) {
return category.name;
} else {
return;
}
})
}
}
})
View:
{{topic.category_id | cardCategories}}

That return statement in the forEach callback function will not return a value from the $scope.cardCategories, it returns something from the callback you provided to forEach (and angular happily ignores it). Try something like this:
$scope.cardCategories = function(id) {
var i = $scope.categoryFilter.length; // assuming it's an array
while(i--) {
if($scope.categoryFilter[i].id === id) {
return $scope.categoryFilter[i].name;
}
}
};
Also -- there's no way to break (stop early) an angular.forEach loop, so for performance reasons it's better to avoid it if you're locating something inside an array/object.

You need to make sure the forEach loop doesn't do a return if the current iteration doesn't match the ID you passed in.
Take out the else condition from your if statement
$scope.cardCategories = function(id) {
angular.forEach($scope.categoryFilter, function(category, index){
if (category.id == id) {
return category.name;
}
});
};

Related

Removing element from array in class method

I was working on a hackerrank problem and test cases showed that something was wrong with my 'remove' method. I always got undefined instead of true/false.
I know splice returns array of deleted elements from an array. When I console.log inside map, it looked like everything was fine when I was deleting first element (I was getting what I expected except true/false). But when 'name' I am deleting is not first element, I didn't get what I expected to get. Could you help me fix this? And of course, I never get true or false...
class StaffList {
constructor() {
this.members = [];
}
add(name, age) {
if (age > 20) {
this.members.push(name)
} else {
throw new Error("Staff member age must be greater than 20")
}
}
remove(name) {
this.members.map((item, index) => {
if(this.members.includes(name)) {
console.log(name)
let removed = this.members.splice(item, 1);
console.log(removed)
return true;
} else {
return false;
}
})
}
getSize() {
return this.members.length;
}
}
let i = new StaffList;
i.add('michelle', 25)
i.add('john', 30);
i.add('michael', 30);
i.add('jane', 26);
i.remove('john');
console.log(i);
Your return statements are wrapped within .map() (which you misuse in this particular case, so you, essentially, build the array of true/false), but your remove method does not return anything.
Instead, I would suggest something, like that:
remove(name){
const matchIdx = this.members.indexOf(name)
if(matchIdx === -1){
return false
} else {
this.members.splice(matchIdx, 1)
return true
}
}
In the remove method, you're using map with the array, which runs the function you give as argument for each array element. But I believe you don't want to do that.
Using the example you have bellow, basically what you do there is check if the array contains the name 'john', and if so, you delete the first item that appears in the array (which would be 'michelle'). This happens because the map function will run for every element, starting on the first one, and then you use that item to be removed from the array. After that, it returns the function, and no other elements get removed.
So my suggestion is just getting rid of the map function and running its callback code directly in the remove method (you would need to get the name's index in the array to use the splice method).
It is not clear why you need to use iterative logic to remove an item. You can simply use findIndex() to get the position of the member in the array. If the index is not -1, then you can use Array.prototype.slice(index, 1) to remove it. See proof-of-concept example below:
class StaffList {
constructor() {
this.members = [];
}
add(name, age) {
if (age > 20) {
this.members.push(name)
} else {
throw new Error("Staff member age must be greater than 20")
}
}
remove(name) {
const index = this.members.findIndex(x => x === name);
if (index !== -1) {
this.members.splice(index, 1);
}
}
getSize() {
return this.members.length;
}
}
let i = new StaffList;
i.add('michelle', 25)
i.add('john', 30);
i.add('michael', 30);
i.add('jane', 26);
i.remove('john');
console.log(i);
Use a filter method instead of map it's more elegant and you can return the rest of the array as well instead of true or false unless the problem you're working on requires true of false specifically.
You could write something like this:
remove(name) {
if (!this.members.some(el => el === name)) return false;
this.members = this.members.filter(item => item !== name);
return true;
}

Backbone.js - Object doesn't support property or method 'each'

I'm very inexperienced with Backbone, but have inherited another dev's code to maintain. I'm trying to add some new functionality to a model. Here's what I have so far:
var AfeDetailCollection = Backbone.Collection.extend(
{
model: AfeDetailModel,
getSubtotalUSD: function(){
return _.reduce(this.models, function(memo, model, index, list){
return memo + model.getExtCostUSD();
}, 0, this);
},
getSubtotalLocal: function () {
return _.reduce(this.models, function (memo, model, index, list) {
return memo + model.getExtCostLocal();
}, 0, this);
},
hasMixedCurrency: function () {
var currCode = '';
this.models.each(function (model) {
if (currCode == '')
// Identify the currencyCode of the first AfeDetail object in the collection
currCode = model.get('currencyCode');
else if (currCode != model.get('currencyCode'))
// The currencyCode has changed from prior AfeDetail in the collection
return true;
});
return false;
}
}
);
The hasMixedCurrency() function is what I've added. The two pre-existing functions work fine. What I'm trying to do is determine whether the collection of AfeDetail objects contains multiple currencyCode values (a property on the AfeDetail model). So I was simply trying to iterate through this collection until I find a change in the currencyCode and then return true.
In the javascript on my page, however, as soon as I try to check this...
if (this.collection.hasMixedCurrency()) {
...
...I get this: Error: Object doesn't support property or method 'each'
I'm obviously doing something wrong, probably something simple, but I'm just not seeing it.
It is look like this.models is a javascript array, not a backbone collection.
You can try with underscore's each method:
_.each(arr, function(val) {
});
Also your logic in loop looks wrong. Try this code:
hasMixedCurrency: function() {
return _.size(_.uniq(this.models, "currencyCode")) > 1;
}
jsFiddle
Edit: More performanced way
hasMixedCurrency: function () {
return _.find(this.models, function(v) { return v.currencyCode !== _.first(this.models).currencyCode; }) !== undefined;
}

React - Filtering returns wrong rows

It's driving me crazy. I've created a list with several entries. I added a filtering function, which seems to work fine. I've checked the number of results returned, but somehow it just showing the result number beginning at the first row.
For explanation:
Let's assume I search for "Zonen" and my filter function returns 4 rows with ID 23, 25, 59 and 60, the rows with ID's 1,2,3 and 4 are displayed. What I'm doing wrong!?
...
render() {
let filteredList = this.state.freights.filter((freight) => {
let search = this.state.search.toLowerCase();
var values = Object.keys(freight).map(function(itm) { return freight[itm]; });
var flag = false;
values.forEach((val) => {
if(val != undefined && typeof val === 'object') {
var objval = Object.keys(val).map(function(objitm) { return val[objitm]; });
objval.forEach((objvalue) => {
if(objvalue != undefined && objvalue.toString().toLowerCase().indexOf(search) > -1) {
flag = true;
return;
}
});
}
else {
if(val != undefined && val.toString().toLowerCase().indexOf(search) > -1) {
flag = true;
return;
}
}
});
if(flag)
return freight;
});
...
<tbody>
{
filteredList.map((freight)=> {
return (
<Freight freight={freight} onClick={this.handleFreightClick.bind(this)} key={freight.id} />
);
})
}
</tbody>
...
UPDATE
freights is loaded and filled via AJAX JSON result. One object of freights looks like this:
I have a textbox where a user can perform a search. This search should return all freight objects which properties contain the search string.
The filter is so complex, because I want to also to search in sub-objects of freight. Maybe there is a more simple way?
"Zones" was just an example for a search string the user can search for.
Now that your intentions are clearer, I suggest this much less complex solution.
First, you can write a recursive utility fn to get all values of all keys in an n-depth object. Like this, for example (I'm using lodash's utility fn isObject there):
const getAllValues = (obj) => {
return Object.keys(obj).reduce(function(a, b) {
const keyValue = obj[b];
if (_.isObject(keyValue)){
return a.concat(getAllValues(keyValue));
} else {
return a.concat(keyValue);
}
}, []);
}
Now that you have an array of all object's values, it makes your filter very simple:
let filteredList = this.state.freights.filter((freightItem) => {
const allItemValues = getAllValues(freightItem);
return allItemValues.includes(this.state.search);
});
That should be it. If something is not working, gimme a shout.
I have found the solution why the "wrong" freight entries are displayed.
I needed to add in freight component the componentWillReceiveProps method:
componentWillReceiveProps(nextProps) {
if(nextProps.freight) {
this.setState({
freight: nextProps.freight
});
}
}
Then everything worked fine.

Javascript break/return function within function

I have always been confused about the best way to handle this. The method I have been using in the past works but it seems like there has to be a better way.
Below I have a section of code that I'm wanting to return item for the function getData. Problem is in the example below it's returning for the forEach function not the getData function.
function getData() {
var array = ["element1","element2"];
array.forEach(function (item) {
if (item == "element2") {
return item;
}
});
}
I have been doing something like this to overcome this.
function getData() {
var array = ["element1","element2"];
var returnValue;
array.forEach(function (item) {
if (item == "element2") {
returnValue = item;
}
});
if (returnValue) {
return returnValue;
}
}
Is there a better way to handle this? Seems like those extra 4 lines of code just create confusion and clutter in my code.
You could use Array#some
The some() method tests whether some element in the array passes the test implemented by the provided function.
function getData() {
var array = ["element1","element2"];
var returnValue;
array.some(function (item) {
if (item == "element2") {
returnValue = item;
return true;
}
});
return returnValue;
}
Or, if you use ES6, use Array#find
The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.
function getData() {
var array = ["element1","element2"];
return array.find(item => item == "element2");
}
You can readily do this with Array#indexOf:
function getData() {
var array = ["element1","element2"];
var index = array.indexOf("element2");
return index === -1 ? null : array[index];
}
In that case, it works because what you're looking for is an === match for what you have. The more general case is a case for Array#find, which is an ES2015 thing but you can easily shim/polyfill it for ES5 and below:
function getData() {
var array = ["element1","element2"];
return array.find(function (item) {
return item == "element2";
});
}
...which lets you specify the match based on a more complex condition.
You could just use indexOf:
return array[array.indexOf("element2")];
If it doesn't find the value, the index will be -1. And index -1 of any array will be undefined.

Pass property with dot notation(sometimes) to function

I've got a function that is looking through a specified collection and highlighting the checkboxes for the items that are present in that collection.
function highlightFiltersPresentInTransactions(collection, collectionproperty, child) {
var found = false;
angular.forEach(collection, function (filterType) {
if (scope.vm.transactions) {
found = scope.vm.transactions.filter(function (obj) {
if (child) {
return obj[collectionproperty][child] === filterType.name;
} else {
return obj[collectionproperty] === filterType.name;
}
});
}
if (found) {
filterType['has-transaction'] = (found.length > 0);
}
});
}
I'm able to call it and it correctly works like this
highlightFiltersPresentInTransactions(scope.filterTypes, 'target', 'type');
highlightFiltersPresentInTransactions(scope.actionTypes, 'transactionType');
What I would like to be able to avoid is the check whether there is a child element that needs to be checked.
I attempted to call the function as such:
highlightFiltersPresentInTransactions(scope.filterTypes, 'target.type');
Since this is a string it doesn't find the property. I also tried creating a blank target object then passing target.type without the quotes.
How can I dynamically pass in a property that might or might not have a child property to my function?
How about passing a function reference to the function?
highlightFiltersPresentInTransactions(scope.filterTypes, function(o) { return o.target.type; });
highlightFiltersPresentInTransactions(scope.filterTypes, function(o) { return o.transactionType; });
This can be implemented pretty easily:
function highlightFiltersPresentInTransactions(collection, readFn) {
var found = false;
angular.forEach(collection, function (filterType) {
if (scope.vm.transactions) {
found = scope.vm.transactions.filter(function (obj) {
return readFn(obj) === filterType.name;
});
}
if (found) {
filterType['has-transaction'] = (found.length > 0);
}
});
}
If you don't want to do that, one way or another you'll have to split your string target.type into separate properties, and do it your existing way (just without the explicit parameter for child).

Categories

Resources