flatMap()
- это .map()
и .flat()
вместе взятые.Он может действовать как обратный .filter()
, напрямую возвращая или не возвращая значения.Подробности смотрите в демоверсии.
const items = [{
id: 'a',
pn: 'B',
desc: ''
}, {
id: 'b',
pn: 'c',
desc: 'd'
}, {
id: 'c',
pn: 'k',
desc: null
}, {
id: 'i',
pn: 'k',
desc: 2
},, {
id: 'o',
pn: 'x',
desc: 3
}];
// Utility function that returns a 'friendlier' value
function clean(obj) {
return obj == null ? false : Array.isArray(obj) ? obj : obj.constructor.name.toLowerCase() === "object" ? obj.toString().trim().toLowerCase() : typeof obj === "string" ? obj.toString().trim().toLowerCase() : Number(parseFloat(obj)) === obj ? obj : false;
}
// Filters by a single key and multiple values
let filterKey = clean('desc');
let filterVal = clean(['d', 2, 'f']);
/* It returns each value in a sub-array an empty array will remove
the value. In the final stage it flattens the array of arrays into a normal array
*/
let list = items.flatMap(item => {
return Object.entries(item).flatMap(([key, value]) => filterKey === (clean(key)) && [...filterVal].includes(clean(value)) ? [clean(value)] :[]);
});
console.log(list);