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';
});
2
  • Yes. Use bracket notation. Commented Feb 15, 2021 at 8: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? Commented Feb 15, 2021 at 8:26

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.