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
5 Answers 5
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).
Comments
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 != ''));
Comments
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)
Comments
This questions is already answered in below link, Please have a look
Click here!
Comments
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);
removeEmpty?arrshadows thearrin the closure. You should rename the parameter, and decide whether you want to use the variable from the closure or the parameter (likely the latter, or you wouldn't need a parameter at all).arr.filter(val => val.value);