How I can skip the element of array .map?
This is what Array.prototype.filter()
is for. You need to do this in two steps.
var userids = userbody.contacts
.filter(contact => contact.iAccepted == 'true' && contact.contactAccepted == 'true')
.map(contact => contact.userId);
The filter part takes out all unnecessary elements, then map converts the rest to the way you want.
you can use flatMap
The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.
var userids = userbody.contacts.flatMap((obj)=>{
if((obj.iAccepted=='true')&&(obj.contactAccepted=='true')) {
return obj.userID
}
else{
return[];
}
});
You can use Array.reduce
function to implement Array.map
and Array.filter
process in one function as follows.
const userIds = userbody.contacts.filter((acc, cur) => {
if((obj.iAccepted == 'true') && (obj.contactAccepted == 'true')) {
acc.push(obj.userID);
}
return acc;
}, []);
console.log(userIds);