简体   繁体   中英

Perform conditional map join

I have to join an array of javascript object property, but to add the property value to the string I have to check if another property is not undefined or false :

What I do now:

var out = [];
$scope.grid.dataSource.data().map(function (user) {
  if (angular.isDefined(user.Selected) && user.Selected == true)
    out.push(user.UserPersonID);
});

var ids = out.join(",");

I'd like do something like this:

var ids = $scope.grid.dataSource.data().map(function (user) { if (user.Selected) return user.UserPersonID; }).join(",");

But if the user.Selected is not true I'll obtain a long list of , ('123,,,234,,,').

How can I get the same result without using the out array?

You're looking for the Array filter method :

var out = $scope.grid.dataSource.data().filter(function(user) {
    return angular.isDefined(user.Selected) && user.Selected;
}).map(function (user) {
    return user.UserPersonID;
});

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