如何在对象数组中查找和编辑对象的属性?

时间:2015-12-09 15:24:51

标签: javascript angularjs

我有一系列对象,我想找到属性' plane:true'在某些对象中并将其设置为false。它只是将数组添加到与对象相同的区域。我尝试使用angular forEach()函数,但没有任何反应。请帮助。



this.typeTransport = [
      {
        currentTransport: 'plane',
        changeTransport: 'plane_disable',
        plane: true
      },
      {
        currentTransport: 'train',
        changeTransport: 'train_disable',
        train: true
      },
      {
        currentTransport: 'bus',
        changeTransport: 'bus_disable',
        bus: true
      },
      {
        currentTransport: 'ship',
        changeTransport: 'ship_disable',
        ship: true
      }
    ];

angular.forEach(this.typeTransport, function(value, key){
          angular.forEach(value, function(value, key){
            if(key === 'plane'){
    this.typeTransport[key] == false ? this.typeTransport[key] = true : this.typeTransport[key] = false;
              console.log(this.typeTransport);
            }
          });
      });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;
&#13;
&#13;

6 个答案:

答案 0 :(得分:1)

使用Array.prototype.forEach()

的普通Javascript解决方案
  

forEach()方法每个数组元素执行一次提供的函数。

var typeTransport = [{ currentTransport: 'plane', changeTransport: 'plane_disable', plane: true }, { currentTransport: 'train', changeTransport: 'train_disable', train: true }, { currentTransport: 'bus', changeTransport: 'bus_disable', bus: true }, { currentTransport: 'ship', changeTransport: 'ship_disable', ship: true }];

typeTransport.forEach(function (a) {
    if (a.plane) {
        a.plane = false;
    }
})

document.write('<pre>' + JSON.stringify(typeTransport, 0, 4) + '</pre>');

答案 1 :(得分:1)

问题是typeTransport是一个数组和&#39;飞机&#39;不是它的属性,里面的对象具有属性&#39; plane&#39;

将内部forEach重命名为value1,key1

 angular.forEach(this.typeTransport, function(value, key) {
 angular.forEach(value, function(value1, key1) {

 if (key1 === 'plane') {
      this.typeTransport[key][key1] = false;
    }
  });
 });

根据您的条件,如果为true,则设置为false,以上条件有效。如果你需要make true =&gt; false&amp; false =&gt; true,然后是条件

 this.typeTransport[key][key1] = !this.typeTransport[key][key1];

答案 2 :(得分:1)

你有两个forEach循环。

在第二个循环中,您必须引用每个单独的项而不是数组

template <class T>
class CValueEdit : public CValueEditBase 
{
public:
    virtual type_e type(void) const { return std::is_integral<T>::value ? int_e : float_e) ; }
...
} ;

答案 3 :(得分:0)

我不确定,理解你的问题,但这应该有效。

this.tranportType.forEach(function(tt){
     if(tt.hasOwnProperty('plane') && tt.plane){
        tt.plane = false; 
     }
})

答案 4 :(得分:0)

只是添加一些旧学校&#39; :)

for (var i = 0; i < this.typeTransport.length; i++) {
  if (this.typeTransport[i].plane == true) {
    this.typeTransport[i].plane = false;
  }
}

答案 5 :(得分:0)

您仍然可以使用angular.forEach,只需更改一下:

angular.forEach(typeTransport, function(value){
    if(value.plane){
        value.plane = false;
    }
});

这样您的模型就会更新,而无需致电$scope.$apply();

这是fiddle

相关问题