0

I have multiple input checkboxs created from a model with angular using ng-repeat, when I select some of them I get this:

var accounts = [{'AA764':true}, {'AA324': true}, {'AA234': false}, {'AA553': true}, {'AA7365': false}];

But I need following structure to manipulate in controller that calls and REST API:

var accounts = ['AA764', 'AA324', 'AA553'];

Just those checkboxes that are selected, I have tried with the javascript foreach function but I cannot make it work. Is there any library for angular or maybe with bower that can help me?

Thanks.

3
  • 1
    I'm not sure about the first array you are describing. Are you sure it is that way. I think it must be something like: var accounts = [{'AA764':true},{ 'AA324': true},{ 'AA234': false},{ 'AA553': true}, {'AA7365': false}]; Am I right? Commented Mar 2, 2016 at 3:51
  • you are right, I corrected it. Commented Mar 2, 2016 at 3:54
  • @AndreFontaine see the edited question for proper array syntax and see my answer if it satisfies requirement, let me know if still there is any change required. Commented Mar 2, 2016 at 4:15

7 Answers 7

2

try this code, i'm using lodash library here:

var accounts = [{'AA764':true}, {'AA324': true}, {'AA234': false}, {'AA553': true}, {'AA7365': false}];
_.compact(accounts.map(transform));

function transform(item) {
  var prop = Object.keys(item)[0];
  return item[prop] ? prop : false;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you don't mind using a library, jQuery.map() works well for this:

var accounts = [{'AA764':true}, {'AA324': true}, {'AA234': false}, {'AA553': true}, {'AA7365': false}];
var trueAccounts = $.map(accounts, function(item) {
  var key = Object.keys(item)[0];
  if (item[key])
    return key;
  else
    return null;
});
console.log(trueAccounts);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Or, to do it in straight JavaScript you can combine Array.filter() with Array.map():

var accounts = [{'AA764':true}, {'AA324': true}, {'AA234': false}, {'AA553': true}, {'AA7365': false}];
var trueAccounts = accounts.filter(function(item) {
  var key = Object.keys(item)[0];
  return item[key];
}).map(function(item) {
  return Object.keys(item)[0];
});
console.log(trueAccounts);

Comments

0

I think this might help you:

var accounts = [{'AA764':true},{ 'AA324': true},{ 'AA234': false},{ 'AA553': true}, {'AA7365': false}];

// Get selected objects
function getSelected(accounts){

    var ans = [];

    // Looping through array
    for(var i = 0; i < accounts.length; i++){

        var item = accounts[i];

        // Looping over object dynamic property
        for(var prop in item){
            if(item.hasOwnProperty(prop)){

                // if property is true then add it to the answer array
                if(item[prop] === true){
                    // Add item to the answer array
                    ans.push(item);
                }
            }
        }            
    }

    return ans;
}

console.log(getSelected(accounts)); // Here you may see the answer

As you can see above, this is looping through the array of objects, then looping through the objects properties (only one) and checking if that property is set to true and add it to the answer array.

Comments

0

This is a simple and fast solution:

// Input values
var accounts = [{'AA764':true}, {'AA324': true}, {'AA234': false}, {'AA553': true}, {'AA7365': false}];

// Result
var accountsResult = [];

// Loop through the array items
for (var i = 0; i < accounts.length; i++) {
  // Loop through the object properties
  Object.keys(accounts[i]).forEach(function (key) {
    // Check if the value is true
    if (accounts[i][key]) { 
      // If it is true add to the resulting array
      accountsResult.push(Object.keys(accounts[i])[0]);
    }
  });
}

// Voilà, you have your result in a new array
console.log(accountsResult);

Comments

0

If you want to go for library, Very useful one is here Check-list model

Or Do it with this way!

angular.module('app', [])
.controller('Ctrl', function($scope){
  $scope.accounts = {AA324: false, AA234: false, AA553: false, AA764: true };
  $scope.showBeforeSendingRestAPI = function(){
    var res = []; 
    for(var i in $scope.accounts){
      if($scope.accounts[i])
        res.push(i);
     } 
    return res;
  } 
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller="Ctrl">
  <label ng-repeat="(account, checked) in accounts">
      <input type="checkbox" ng-model="accounts[account]" />         {{account}} 
  </label>
  <p>Accounts: {{showBeforeSendingRestAPI()}}</p>
</div>

Comments

0

You can do it this way as well.

<ul>
  <li ng-repeat="account in accounts">
    <input type="checkbox" ng-model="account.selected" value={{account.name}} />
  </li>
</ul>

function abc(){
$scope.accountsArray = [];
      angular.forEach($scope.accounts, function(account){
        if (!!account.selected) $scope.albumNameArray.push(account.name);
      })
}

Comments

0

You can use a Library called Lodash. Its a utility library that gives lots of functions to make tasks like this simple. Although this can be done using pure JS I will use this library considering its usability in other scenarios.

You can use this:

var accounts = [{'AA764':true},{ 'AA324': true},{ 'AA234': false},{ 'AA553': true}, {'AA7365': false}];
var a =_.filter(_.map(accounts, function(item){
  return _.findKey(item);
}),undefined);
console.log(a);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js"></script>

Result:

enter image description here

This function iterates over an object and creates an array containing only the keys in the object.For more info on function:

https://lodash.com/docs#findKey

https://lodash.com/docs#map

https://lodash.com/docs#filter

You can include the library from CDN(https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js) or download and use it as normal script. Lodash offers plenty of useful utility functions that makes JS programming a lot easier. You better try it out.

1 Comment

I took the liberty to make this answer into a snippet. I think it's a lot more helpful to see this in action rather than just a screenshot of console output. P.S. I actually upvoted this answer--I'm not sure why it was downvoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.