Javascript 如何在对象数组中查找和编辑对象的属性?
我有一个对象数组,我想在一些对象中找到属性“plane:true”,并将其设置为false。它只是将对象添加到同一区域的数组中。我试图使用angular forEach()函数,但什么也没发生。请帮忙Javascript 如何在对象数组中查找和编辑对象的属性?,javascript,angularjs,Javascript,Angularjs,我有一个对象数组,我想在一些对象中找到属性“plane:true”,并将其设置为false。它只是将对象添加到同一区域的数组中。我试图使用angular forEach()函数,但什么也没发生。请帮忙 this.typeTransport=[ { currentTransport:'飞机', changeTransport:“飞机禁用”, 飞机:对 }, { 当前运输:“火车”, changeTransport:“列车禁用”, 火车:是的 }, { 当前传输:“总线”, changeTrans
this.typeTransport=[
{
currentTransport:'飞机',
changeTransport:“飞机禁用”,
飞机:对
},
{
当前运输:“火车”,
changeTransport:“列车禁用”,
火车:是的
},
{
当前传输:“总线”,
changeTransport:“总线禁用”,
巴士:是的
},
{
currentTransport:'船舶',
changeTransport:'ship_disable',
船:是的
}
];
angular.forEach(this.typeTransport,函数(值,键){
角度。forEach(值,函数(值,键){
如果(键=='plane'){
this.typeTransport[key]==false?this.typeTransport[key]=true:this.typeTransport[key]=false;
console.log(this.typeTransport);
}
});
});代码>
我不确定你是否理解你的问题,但这应该行得通
this.tranportType.forEach(function(tt){
if(tt.hasOwnProperty('plane') && tt.plane){
tt.plane = false;
}
})
一个简单的Javascript解决方案
forEach()
方法对每个数组元素执行一次提供的函数
var typeTransport=[{currentTransport:'plane',changeTransport:'plane_disable',plane:true},{currentTransport:'train',changeTransport:'train_disable',train:true},{currentTransport:'ship',changeTransport:'ship_disable',ship:true}];
typeTransport.forEach(函数(a){
如果(飞机){
a、 平面=假;
}
})
document.write(''+JSON.stringify(typeTransport,0,4)+'')代码>只是为了添加一些“老派”:
for(var i=0;i
您仍然可以使用angular.forEach
,只需稍微更改一下:
angular.forEach(this.typeTransport, function(value, key) {
angular.forEach(value, function(value1, key1) {
if (key1 === 'plane') {
this.typeTransport[key][key1] = false;
}
});
});
这样,您的模型将更新,而无需调用$scope.$apply()代码>
这里有一个。问题是typeTransport是一个数组,而“plane”不是数组的属性,其中的对象具有属性“plane”
将内部forEach重命名为value1,key1
this.typeTransport[key][key1] = !this.typeTransport[key][key1];
根据您的条件,如果设置为true,则设置为false,以上条件适用。如果您需要使true=>false&false=>true,那么下面的条件
angular.forEach(this.typeTransport, function(item){
angular.forEach(item, function(value, key){
if(key === 'plane'){
item[key] == false ? item[key] = true : item[key] = false;
console.log(item);
console.log(this.typeTransport);
}
});
});
您有两个forEach循环
在第二个循环中,您必须引用每一项,而不是数组
如果OP希望将train:true
更改为false
,而不是plane:true
:),这可能是一个很好的解决方案
this.typeTransport[key][key1] = !this.typeTransport[key][key1];
angular.forEach(this.typeTransport, function(item){
angular.forEach(item, function(value, key){
if(key === 'plane'){
item[key] == false ? item[key] = true : item[key] = false;
console.log(item);
console.log(this.typeTransport);
}
});
});