0

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';
});
  • Yes. Use bracket notation. – Terry Feb 15 '21 at 08:24
  • you'll need to have some sort of idea of what property you want to access, or else what would you compare against (do you want to compare against all values within the object?). Do you have the property generated dynamically somewhere within your code? – Nick Parsons Feb 15 '21 at 08:26

1 Answers1

2

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209