'Best way to restructure nested if statements
I have the following code:
const config = {
key1: {
outlier: 'outlier1'
},
key2: {
test: 'test'
},
key3: {
outlier: 'outlier3'
}
}
const finalArr = [];
Object.keys(config).forEach((key) => {
const obj = config[key];
// How to make this if/if/else structure cleaner?
if (obj.outlier) {
if (doSomeWithOutlier(obj.outlier)) {
finalArr.push(obj);
}
}else {
finalArr.push(obj);
}
});
Is there a cleaner way to do the above following? It seems like I am nesting the if/if stamenets and else statements to much and duplicating finalArr.push(obj) code.
Solution 1:[1]
You could use:
if ((obj.outlier && doSomeWithOutlier(obj.outlier)) || !obj.outlier) {
finalArr.push(obj);
}
However, I think your structure is easier to read.
You can also loop over Object.values(config) rather than the keys, so you don't need the extra step of const obj = config[key];.
Solution 2:[2]
Alternative:
if (obj.outlier && !doSomeWithOutlier(obj.outlier))
return;
finalArr.push(obj);
Solution 3:[3]
The others showed you how to handle the if/if/else as a single condition to make the code shorter, using Object.values() and .reduce would help to make the code even shorter:
const finalArr = Object.values(config).reduce((arr, el) =>
el.outlier && doSomeWithOutlier(el.outlier) ? [...arr, el] : arr,
[]);
If you want to perform some operation in case .outlier is not present you just change the last statement of ternary operator.
Solution 4:[4]
Hope this'll inspire your solution,
const newConfig = Object.entries(config).reduce((accum, [key, value], idx) => {
// const truthsy = doSomethingWithOutliner(value)
return [...accum, idx%2 === 0 ? 'even' : 'odd']
}, [])
ps: It's not a good practice to name your variables like config and finalArray. Also, you are pushing the same (obj) no matter what.
refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
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 | |
| Solution 2 | Vincent |
| Solution 3 | |
| Solution 4 | pope_maverick |
