Reputation: 1679
Consider a JavaScript array like this:
var testArray=
[
{name:'test1', source: {type:'1' },
{name:'test2',
{name:'test3', source: {type:'1' }
{name:'test4',
{name:'test5', source:{type:'2'},
{name:'test5', source:{type:'3'},
]
I want to filter this array and return all elements except where type===1
. However as you can see, some of the elements don't have the source object.
If I do this:
const filteredData = testArray.filter(itm=>itm.source && itm.source.type !=='1')
It removes elements that don't have a source attribute.
How can I filter this array to retrieve all items except for where there is a source.type !== 1 ?
Upvotes: 0
Views: 57
Reputation: 387
Change your condition to
!itm.source || itm.source.type !== '1'
This will not filter out any items that don't have the source first. All that remain have source so you are safe to check if it is '1'.
Upvotes: 0
Reputation: 73
Try this (note that your array is wrong, some of the objects are not closed "}")
var testArray=[
{name:'test1', source: {type:'1' }},
{name:'test2'},
{name:'test3', source: {type:'1' }},
{name:'test4'},
{name:'test5', source:{type:'2'}},
{name:'test5', source:{type:'3'}},
];
const filteredData = testArray.filter(itm=>!itm.source || itm.source.type !=='1')
Upvotes: 0
Reputation: 89374
You can use the optional chaining operator. It will cause the expression to evaluate to undefined
when trying to access properties on null
or undefined
.
var testArray=
[
{name:'test1', source: {type:'1' }},
{name:'test2'},
{name:'test3', source: {type:'1' }},
{name:'test4'},
{name:'test5', source:{type:'2'}},
{name:'test5', source:{type:'3'}},
]
const filteredData = testArray.filter(itm=>itm.source?.type !=='1');
console.log(filteredData);
Upvotes: 1
Reputation: 128
testArray.filter(i => i.source?.type !== "1")
Will use optional chaining to determine if i.source
exists and then checks if it is equal to "1"
, if it is don't keep it. If not keep it.
Upvotes: 0