Reputation: 201
I have an array of object something like below
Object[0]
canUpload:false
canBeRemoved:true
type:Object
allowMultiple:false
deleted:false
key:"testValue"
Object[1]
canUpload:true
canBeRemoved:true
type:Object
allowMultiple:false
deleted:false
key:"testValue2"
I want to remove an elements from array which contains key:testValue
var myValues = this.testData.data3;
if(!this.testData.canDownload){
myValues= myValues.filter(function(value){
if(!value.canUpload)
return value.type.key==='testValue';
else return false;
});
But its not removing .Whats the right way to do it? Here is the full code .I can see myValues array of size 2 .If i print myValues after if block its empty. Code pen:http://codepen.io/developer301985/pen/woGBNg
Upvotes: 0
Views: 57
Reputation: 10204
Note, if the callback function you passed into filter returns true, the element will be kept rather than removed. So in your case, you should return false when the value is testValue
.
If I understand you correctly, you want to remove item with value.canUpload==false
AND type.key === 'testValue'
. Then the negate is value.canUpload || value.type.key !== 'testValue'
var myValues = this.testData.data3;
if (!this.testData.canDownload) {
myValues = myValues.filter(function(value) {
return value.canUpload || value.type.key !== 'testValue';
});
}
Let me know whether it works :)
Upvotes: 0
Reputation: 2721
If your want to filter your array on the basis of two conditions:
canUpload
attr is falsetype.key
is equal to 'testValue'so you may want to return false
in case of canUpload
is true to be as follow:
myValues= myValues.filter(function(value) {
if(!value.canUpload)
return value.type.key === 'testValue';
else return false;
});
Otherwise, you just want to filter on type.key
is equal to 'testValue', so it will be as follow:
myValues= myValues.filter(function(value) {
return value.type.key === 'testValue';
});
Upvotes: 1