Let us say we have the following array:
const arr = [{
id: 0,
title: 'C',
countries: [{
val: "1173",
label: "Nice"
}, {
val: "1172",
label: "(Yeah)"
}],
companies: [{
val: "7346",
label: "Hello World"
}]
},
{
id: 1,
title: 'B',
countries: [{
val: "1175",
label: "Like it"
}],
companies: [{
val: "8294",
label: "Javascript"
}]
},
]
I would like to do a search for all values that are in this array.
This is my approach:
const objFields = ['countries', 'companies'];
const filterBySearchTerm = (arr, filters) => {
if (!(arr && arr.length)) {
return [];
}
// filters looks like this: {search: 'hello'}
const sT = filters.search;
const searchTermVariations = [sT.toLowerCase()];
console.log(searchTermVariations);
/* Start transform all values to arrays */
const clonedArr = [...arr];
clonedArr.forEach((job) => {
const objKeys = Object.keys(job);
objKeys.forEach((key) => {
const currVal = job[key];
const currValToUse = Array.isArray(currVal) ? currVal : [currVal];
// eslint-disable-next-line no-param-reassign
job[key] = [...currValToUse];
});
});
/* End transform all values to arrays */
/* Start transform all obj-values to plain strings */
const results = clonedArr.filter((itm) => {
const vals = Object.keys(itm).filter((el) => objFields.includes(el));
vals.forEach((key) => {
// eslint-disable-next-line no-param-reassign
itm[key] = itm[key].map((el) => [el.label, el.val]);
});
return vals;
});
/* End transform all obj-values to plain strings */
// perform filtering
console.info('!! results:', results);
return results;
};
I am at the point to say that I find my approach too ugly right now. Do you have an idea how this can be done shorter and more intelligent ?