Reputation: 19
I have an array of objects:
let arr = [{id:0, value: 'zero'},
{id:1, value: 'one'},
{id:2, value: ''}]
I need to remove object with empty value. What I am trying:
const removeEmpty = (arr) => {
let filtered = arr.filter(val => val.value != '');
return filtered;
};
Stuck with this:
TypeError: Cannot read property 'filter' of undefined
Edit: corrected syntax
Upvotes: 0
Views: 572
Reputation: 4570
Following code will be helpful in more cases, for instance if object value is: false, null
, empty string or undefined
.
let arr = [
{id:0, value: 'zero'},
{id:1, value: 'one'},
{id:2, value: ''},
{id:3, value: false},
{id:4, value: null},
{id:5}
];
const filteredArr = arr.filter(obj => obj.value);
console.log(filteredArr);
Upvotes: 0
Reputation: 348
This questions is already answered in below link, Please have a look
Click here!
Upvotes: 0
Reputation: 3386
Seems your arr is not correct i.e object key value pair is not valid
let arr = [{id:0, value: 'zero'}, {id:1, value: 'one'}, {id:2, value: ''}];
const removeEmpty = (arr) => {
let filtered = arr.filter(val => val.value !== '');
return filtered;
}
removeEmpty(arr)
Upvotes: 0
Reputation: 10614
IMHO, you are looking for something like this:
var arr = [{id:0, value: 'zero'}, {id:1, value: 'one'}, {id:2, value: ''}];
var filteredArr = arr.filter(obj => obj.value != '')
console.log(filteredArr);
NOTE: Your's is not a proper array (because Objects
inside it are invalid).
Upvotes: 2
Reputation: 769
You missed a comma on the value of id and a quote for the value of the value
property
let arr = [{id:0, value: "zero"},
{id:1, value: "one"},
{id:2, value: ''}];
console.log(arr.filter(a => a.value != ''));
Upvotes: 0