简体   繁体   中英

Don't display object's data if property doesn't exist

I want to choose not to display an object's data if a property is missing from the object. I'm calling data from a REST API that removes a price_1 property from an object if the item is no longer available for purchase. I've done a little bit of research into delete but from my understanding that's only for deleting a reference to a property, not an object. I'm not sure if it's possible to entirely remove an object if a property doesn't exist, but this would be the ideal solution. I also want to know if the solution would be better suited as a custom filter.

I've tried the following:

angular.module('foldsApp.productModule', [])
    .controller('ProductsController', ['$scope', '$log', 'APIService', function ($scope, $log, APIService) {
        $scope.products = {};

        APIService.getData()
            .success(function(res) {
                $scope.products = res.results;
                for (price in $scope.products) {
                    if($scope.products[price].price_1 === 'undefined') {
                        // remove object?
                    }
                }
            })
            .error(function(data, status, headers, config) {
                $log.log('error: ' + data);
            });

    }]);

Right now, the if($scope.products[price].price_1 === 'undefined') equates to false . I'm not entirely sure why this is happening, but I assume it's because price_1 does exist on most objects in $scope.products and I'm not sure how to work with that. This is my first foray into "higher" level JavaScript, so a few things are going over my head. Any helpful resources are greatly appreciated, thanks.

HTML if that matters:

<ul>
    <li dir-paginate="product in products | itemsPerPage: 30">
        <a href="{{ product.link_1 }}"><img src="{{ product.category_product_image_placeholder_image }}" /></a>
        <br>
        {{ product.product_name_text }}
        <br>
        <strong>{{ product.price_1 | currency }}</strong>
    </li>
</ul>

to check for undefined specifically you should use typeof variable === 'undefined' :

so:

if(typeof $scope.products[price].price_1 === 'undefined'){
    delete $scope.products[price];
}

delete will remove properties of an object (which is what it looks like you have) and if they are not referenced anywhere else the garbage collector will pick them up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM