Reputation: 139
Is it possible to get any property value dynamically in a followed piece of code with a name that we can't predict?
Getting value by object['keyName'] NOT fit here because we DON'T KNOW the property name.
Our property names can be ANY and NOT predictable.
let arr = [{a: 'a'}, {b: 'b'}];
let filtered = [];
filtered = arr.filter(item => {
return item.'some property' === 'a';
});
Upvotes: 0
Views: 44
Reputation: 191976
You can use Object.values()
to get an array of the values, and then use Array.includes()
to check if the requested value is found in the array:
const arr = [{a: 'a'}, {b: 'b'}];
const filtered = arr.filter(item =>
Object.values(item) // get an array of values from the object ['a'] or ['b'] in this case
.includes('a') // check if the array of values contains 'a'
);
console.log(filtered)
Upvotes: 2