I want to filter the object array values based on user input.
This is the jsfiddle:
// Copied from https://github.com/tc39/proposal-object-values-entries/blob/master/polyfill.js
const reduce = Function.bind.call(Function.call, Array.prototype.reduce);
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable);
const concat = Function.bind.call(Function.call, Array.prototype.concat);
const keys = Reflect.ownKeys;
if (!Object.values) {
Object.values = function values(O) {
return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []);
};
}
// Copied code ends here;
let data = {
Belgien: [{
code: "BRU",
name: "Bryssel",
aliases: "Bryssel,BRU,Belgien"
}],
Cypern: [{
code: "LCA",
name: "Larnaca",
aliases: "Larnaca,LCA,Cypern,Ayia Napa,Protaras,Fig Tree Bay,Larnaca"
},
{
code: "PFO",
name: "Paphos",
aliases: "Paphos,PFO,Cypern"
}
]
}
let userInput = "lar";
let filteredData = Object.values(data).map(values => values.filter(value =>
value.name.toLowerCase().indexOf(userInput) !== -1));
console.log(filteredData);
The issue is that I get the values properly filtered, but I do not get the keys associated with these values, in this example the countries.
Thanks in advance.
let filtered = Object.keys(data).map(countryName => { const matches = data[countryName].filter(val => val.name.toLowerCase().match(userInput)); return matches.length ? ({[countryName]: matches}) : null; }).filter(v => v)