Hello I have this function that looks for nested value 3 levels deep currently
// This handle nested data to be applied to filter option which comes from filterProps.prop values
// This is currently chained 3 level deep I.E clock.props.children to add more just keep chaineding
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
return trim
? prop.length === 1
? item[prop[0]] && item[prop[0]].trim().length > 0
: prop.length === 2
? item[prop[0]][prop[1]].trim().length > 0
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]].trim().length > 0
: prop.length === 1
? item[prop[0]] && item[prop[0]]
: prop.length === 2
? item[prop[0]][prop[1]]
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]];
};
I'm trying to figure out a way to reduce the logic and make it simpler. I thinking if it would be a good idea to use get from Lodash https://lodash.com/docs/4.17.15#get
########UPDATE added lodash get to simplify########
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return trim
? prop.length === 1
? L1 && L1.trim().length > 0
: prop.length === 2
? L2 && L2.trim().length > 0
: prop.length === 3 && L3.trim().length > 0
: prop.length === 1
? L1
: prop.length === 2
? L2
: prop.length === 3 && L3;
};
######## UPDATE 2 ########
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};