TL;DR: Can use ['test1', 'test3'].some(field => nonEmptyErrors(data[field])). See how functional JS-patterns work in different solutions.
Chaining conditions
In test1 || test2 || test3 your are chaining tests with boolean OR ||. The boolean OR is short-circuiting, means the first true in evaluation of this chain wins.
The same can be done more flexible using the functional some(predicate) test in JavaScript.
I want to explain some functional ingredients before showing you the solving recipe.
Functional Basics
Arrays in pipelines: Filter, Map, Reduce
JavaScript uses filter to find any objects that satisfy the predicate.
Can combine it with map, reduce as chained methods to build a data-pipeline. This approach is often called "streaming".
Objects to arrays
First you have to get a stream from your object data.
This can be done using factory methods:
Functionals applied
Let's use the functional-basics explained above and build a chained pipeline to test, if your data object has errors.
Finally, we combine following functional ingredients
nonEmptyErrors: use a lambda predicate to filter elements
map, reduce and some as shortcuts (syntactic sugar)
to:
hasErrors(data): a convenient function which returns a boolean
- test selected properties
['test1', 'test3'] only
const data = {
test1: [
{error: ''},
{error: ''},
],
test2: [
{error: ''},
{error: 'theres an error in this field'},
{error: 'theres an error here'},
],
test3: [
{error: ''},
{error: 'theres an error'},
{error: 'theres an error here'},
]
};
// (0) data: tests with array of errors as string, some empty
// (1) define a filter lambda (can be used as function)
let nonEmptyErrors = arr => arr.filter(el => el.error !== '');
// (2) count specific elements with map-reduce
let countNonEmptyErrors = Object.entries(data)
.map(([key, value]) => {
let errors = nonEmptyErrors(value);
console.log(key, errors.length);
return errors;
})
// sum/count elements
.reduce((acc, elem)=>{acc += elem.length; return acc;}, 0);
// .flat().length;
console.log("countNonEmptyErrors", countNonEmptyErrors);
// (3) reuse the filter as predicate in a convenient function
function hasErrors(data) {
return Object.values(data).some(nonEmptyErrors);
}
console.log("data has errors?", hasErrors(data));
// (4) filter selected properties of an object
console.log("test1, test3 | any errors: ",
['test1', 'test3'].some(field => nonEmptyErrors(data[field]))
);
ifattribute in HTML it looks like angular .. correct ? Then there is a little trick you oversaw 😉️