简体   繁体   中英

JS - Getting object property value

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';
});

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM