问题描述:

I'm building a form to interact with a remote API by building a GET request query string based on what checkboxes the user selects.

My initial thought was to do a laundry list of if/else checks to see if the model object key is true or not and then make a clean array out of just the object key names. However, would there be a more automated way to do it?

I was thinking something along the lines of an angular.foreach, but I can't figure out how to get the object key names to come out as a value.

For example:

function submit() {

var pushData = [];

angular.foreach(vm.export, function(item, index){

if (item == true) {

pushData[item];

}

})

}

Here is the object it's pulling from:

vm.export = {

'servers': true,

'apps': false,

'users': true,

'userID': 1234

}

How can I push the key names with TRUE values to the pushData array?

网友答案:

The foreach has an item (the object/primitive in the array) and a key. so your pushData is getting a key called "true"(the value of item) instead of the name(the key).

var pushData = [];
angular.foreach(vm.export, function(item, key){
if (item === true) {
    pushData[key];
  }
});
网友答案:

Why not just use a for in loop?

Working Example

function submit(){
  var pushData = [];
  for (var prop in data) {
    if (data[prop] === true) {
      pushData.push(prop);
    }
  }
  return pushData;
}
相关阅读:
Top