[英]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.通过 object['keyName'] 获取值不适合这里,因为我们不知道属性名称。
Our property names can be ANY and NOT predictable.我们的属性名称可以是 ANY 且不可预测。
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:您可以使用Object.values()
获取值的数组,然后使用Array.includes()
检查是否在数组中找到请求的值:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.