JS Array.find if undefined element - javascript

I try to merge two arrays:
productsAll = parserArrayFull.map((item) => {
return {
...item,
...firestoreArrayFull.find((y) => y.productSKU === item.SELLER_SKU),
};
});
Everything works OK if in "firestoreArrayFull" there is "productSKU" with the same value like item.SELLER_SKU. But if not there is error
"Cannot read property 'productSKU' of undefined"
How to make condition for this situation? I would like to keep "item" only in the case of error.
regards

Looks like you have some null values in firestoreArrayFull array.
Try put y && before you make a comparison to make sure y isn't null or undefined.
productsAll = parserArrayFull.map((item) => {
return {
...item,
...firestoreArrayFull.find((y) => y && y.productSKU === item.SELLER_SKU),
};
});
Update
If not found, adds productSKU property equals to item.SELLER_SKU.
productsAll = parserArrayFull.map((item) => {
return {
...item,
...(firestoreArrayFull.find((y) => y && y.productSKU === item.SELLER_SKU) || { productSKU: item.SELLER_SKU }),
};
});

Related

Converting chain conditional operators to old check method

I'm having to convert my inline conditional operators in my node js application as they're not supported by PM2. I'm a little stuck on why one of my lines isn't converting correctly.
The current conditional chaining operators returns the correct result
// Working solution
purchases.forEach((purchase) => {
const matchingItems = sales.filter(obj => obj.elements[0]?.specialId === purchase.elements[0]?.specialId);
if (matchingItems.length > 0){
console.log('purchase has been SOLD.')
purchase.sold = true
}
})
but my converted code is not returning 'purchase has been sold'
purchases.forEach((purchase) => {
// const matchingItems = sales.filter(obj => obj.elements[0] && obj.elements[0].specialId === purchase.elements[0] && purchase.elements[0].specialId);
const matchingItems = sales.filter((obj) => {
return obj.elements[0] && obj.elements[0].specialId === purchase.elements[0] && purchase.elements[0].specialId
})
if (matchingItems.length > 0){
console.log('purchase has been SOLD.')
purchase.sold = true
}
})
https://jsfiddle.net/nia232/yugcw326/6/
I'm sure it's something obvious im doing wrong but any help appreciated!

Checking existing array have given value or not

In following code i have define empty array houseTotal, now I would like to push value inside array which is unique and not exist previously. I have use some, unique, sort filter but its pushing all the value it gets. Here is my code:
let houseTotal = [];
await rel.map((each, index) => {
if (
!isEmpty(each.house_detail) ||
!houseTotal.some(el => el === each.house_detail._id)
) {
houseTotal.push(each.house_detail._id);
}
});
return houseTotal.length;
What I have done mistake here ? Thank you.
If houseTotal is to have UNIQUE values and no duplicates.. I'm going to assume "duplicates" can be == each other and I'll use the Array.includes function
let houseTotal = [];
await rel.map((each, index) => {
if (
!isEmpty(each.house_detail) ||
!houseTotal.some(el => el === each.house_detail._id)
) {
let detail=each.house_detail._id
if(!houseTotal.includes(detail)){houseTotal.push(detail);}
}
});
return houseTotal.length;
And I got the solution, it was small mistake I have made on above code, I forgot to change object id returning from mongo to string so just added toString().
let houseTotal = [];
await rel.map((each, index) => {
if (
!isEmpty(each.house_detail) ||
!houseTotal.some(el => el === each.house_detail._id.toString())
) {
houseTotal.push(each.house_detail._id.toString());
}
});
return houseTotal.length;

Map inside map not changing the original array

Currently I am mapping through and array and then doing a second map to try to remove unwanted objects from the second array.
const activities = self.periods.map(period => {
period.activities.map(activity => {
let showActivity = false
if(activity.teacher_id === teacherId){
showActivity = true
}
else if(activity.substitute){
if(
activity.substitute.type === 'tutor' &&
activity.substitute.id == tutorId
){
showActivity = true
}
else if(
activity.substitute.type === 'teacher' &&
activity.substitute.id == teacherId
){
showActivity = true
}
}
if(showActivity){
return activity
}
else{
return null
}
})
return period
})
Currently it just seems to return the periods array exactly as it is despite the fact that the if statement that returns null does get triggered.
Array.map returns the same length of array as the original array. You should use Array.forEach.
const activities = []
self.periods.forEach(period => {
...
if (...) {
activities.push(period)
}
})

TypeError: params[item].split is not a function

Console outputs ERROR TypeError: params[item].split is not a function. Any help is appreciated. The best help would be to understand my error in approaching this problem.
routeReady() {
this.activeRoute.queryParams
.pipe(switchMap(params => {
if (!params['filter']) {
// use previous month as default
let date : Date = new Date();
date.setDate(1);
date.setMonth(date.getMonth() - 1);
this.formData.startDate = DateUtils.dateToText(date);
date.setDate(DateUtils.getDaysInMonth(date));
this.formData.endDate = DateUtils.dateToText(date);
}
['startDate', 'endDate', 'club'
, 'subscription', 'sold'].forEach(item => {
if (item in params && params[item] !== '') {
this.formData[item] = params[item];
}
});
['courts', 'groups', 'zones'].forEach(item => {
if (item in params && params[item] !== '') {
this.formData[item] = params[item].split(',');
}
});
return Promise.resolve(true);
}))
.subscribe();
}
This is my error:
That's because its not a regular object. Its some angular magic thing-o.
To get the value you have to do.
params.get('whatever property');
in your case
params.get(item).split(',');
Extending what I would do in your case.
['courts', 'groups', 'zones'].forEach(item => {
const value = params.get(item);
if (value) {
this.formData[item] = value.split(',');
}
});
This code assumes params[item] is a string:
this.formData[item] = params[item].split(',')
JavaScript string's have a split method:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
If it is not a string it won't have a split method and thus you will get told:
params[item].split is not a function
To check it's type do:
console.log('params[item]', params[item], typeof params[item])

Uncaught TypeError: Cannot read property 'get' of null in map function

I have findPlayerWithID function which return matched player id
function findPlayerWithID(players, id) {
let i = 0;
for (; i < players.count(); i++) {
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
if (players.map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
}
return -1;
}
But sometimes it give error in this line
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
error is
gameStore.js:38 Uncaught TypeError: Cannot read property 'get' of null
at gameStore.js:38
at immutable.js:3018
at Ue.__iterate (immutable.js:2208)
at r.__iterateUncached (immutable.js:3017)
at F (immutable.js:606)
at r.T.__iterate (immutable.js:322)
at r.toArray (immutable.js:4260)
at new Ue (immutable.js:2067)
at _t (immutable.js:3572)
at Ue.map (immutable.js:4403)
I think error because of null object
How can I check null in this line
if (players.map((degisken) => degisken.get('id')).
immutable.js:1317 Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
Updated
with #canaan-seaton answear I change
this
if (players.filter(degisken => degisken !== null).map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
this work
but it give another error in immutablejs
Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
at this line in immutablejs
function(m ) {return typeof m.merge === 'function' ?
I searcg for that error
there is some info but I don't understand what should I do https://github.com/facebook/immutable-js/issues/597
here is my console
Generally , it is not a good practice to check for equality to undefined.
I would try to do it this way:
First of all, to make sure that degisken does exists you can go with degisken && degisken.get(id)
Second, you might want to use Object's hasOwnProperty method, which will be useful in here:
players.map((degisken) => {
const id = degisken && degisken.get('id');
if(id && id.hasOwnProperty('_tail') && id._tail.array[i] === id){
return i
}
});
if you just want to check if the array has elements then you can do something like the following....
if (players && players.length > 0) {/* Do Stuff */}
if you are concerned with specific indices within the array being null then you could do something like this....
if (players.filter(degisken => degisken !== null)
.map((degisken) => degisken.get('id'))._tail === undefined)
{/* Do Stuff */}

Categories

Resources