'JavaScript, different if made with one object mapped
Currently I have this code:
if (downloadReports.current && socialAssistant.socialattentions?.url) {
window.open(socialAssistant.socialattentions.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsRecords?.url) {
window.open(socialAssistant.socialattentionsRecords.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsAdvices?.url) {
window.open(socialAssistant.socialattentionsRecordReviews.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsRecordReviews?.url) {
window.open(socialAssistant.socialattentionsRecordReviews.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsGroups?.url) {
window.open(socialAssistant.socialattentionsGroups.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsGroupattendants?.url) {
window.open(socialAssistant.socialattentionsGroupattendants.url, '_blank');
}
How can I do a shorten code for that?
socialAssistant is an object that could contain different properties, so depending on those property is the paraemeter to use in window.open method.
I was thinking in something like:
const someVar = ? // how to get which property has?
if (downloadReports.current && someVar) {
window.open(someVar, '_blank')
}
Solution 1:[1]
Loop through all the properties of socialAssistant.
if (downloadReports.current) {
Object.values(socialAssistant).forEach(({url}) => url && window.open(url, "_blank"));
}
Solution 2:[2]
If you expect there to only be one property (or in case of multiple, the first one would be correct), you could use Object.values and use the first:
const url = Object.values(socialAssistant)[0]?.url
if (downloadReports.current && url) {
window.open(url, '_blank')
}
Or, if you want to keep the current logic of opening multiple windows if there are multiple properties, you could it iterate over all (note however that browser won't allow opening more than one new tab at once by default):
if (downloadReports.current) {
for (const { url } of Object.values(socialAssistant)) {
if (url) window.open(url, '_blank')
}
}
Or, if you want to stay even closer to the current logic in that only certain properties should be considered, you could iterate over an array of possible properties:
if (downloadReports.current) {
for (const property of [
'socialattentions',
'socialattentionsRecords',
'socialattentionsAdvices',
'socialattentionsRecordReviews',
'socialattentionsGroups',
'socialattentionsGroupattendants'
]) {
const url = socialAssistant[property]?.url
if (url) window.open(url, '_blank')
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
| Solution 2 | CherryDT |
