json - 用于循环和 hasOwnProperty 的 ecma 脚本有一个奇怪的行为
问题描述
我想使用 DTO 转换从 NoSQL 数据库获取的对象,因此,我在for..in
循环中检查对象以仅获取我想要保留的内容:
for (const attribute in result) {
if (result.hasOwnProperty(attribute)) {
console.log(`${attribute} belongs to object!`);
}
}
我想知道为什么 :
hasOwnProperty
当我遍历对象以获取属性时,我必须使用方法- 我的对象有一个“营养”属性,但是......从来没有安慰过
这是原始对象的一部分:
...
nutriments:
{ sugars: 6.5,
'nova-group_serving': 4,
fiber_value: 2.5,
'nutrition-score-uk_100g': 1,
energy_value: 1160,
salt_100g: 1.08,
'nutrition-score-uk': 1,
fiber_100g: 2.5,
proteins: 8.5,
'nova-group_100g': 4,
carbohydrates_unit: 'g',
'saturated-fat_100g': 0.4,
'nutrition-score-fr_100g': 1,
salt_unit: 'g',
'saturated-fat_unit': 'g',
sugars_100g: 6.5,
sugars_value: 6.5,
'saturated-fat_value': 0.4,
carbohydrates_value: 49.2,
fat_unit: 'g',
fiber: 2.5,
proteins_value: 8.5,
fat_value: 4.3,
sugars_serving: 5.13,
sodium_value: 0.43200000000000005,
fiber_serving: 1.98,
sodium_unit: 'g',
energy_serving: 916,
sodium_serving: 0.34099999999999997,
proteins_unit: 'g',
carbohydrates: 49.2,
energy: 1160,
salt_value: 1.08,
sodium_100g: 0.43200000000000005,
'nova-group': 4,
'saturated-fat_serving': 0.316,
proteins_serving: 6.72,
'nutrition-score-fr': 1,
energy_100g: 1160,
energy_unit: 'kJ',
fiber_unit: 'g',
'carbon-footprint-from-known-ingredients_product': 416,
sugars_unit: 'g',
proteins_100g: 8.5,
'carbon-footprint-from-known-ingredients_100g': 75.6,
carbohydrates_serving: 38.9,
salt_serving: 0.8530000000000001,
fat_serving: 3.4,
salt: 1.08,
carbohydrates_100g: 49.2,
'saturated-fat': 0.4,
fat_100g: 4.3,
fat: 4.3,
'carbon-footprint-from-known-ingredients_serving': 59.7,
sodium: 0.43200000000000005 },
...
我编辑我的 for in 循环以跟踪“属性”并列出了属性“营养”,但是......result['nutriments']
未定义并result.hasOwnProperty('nutriments')
返回错误......
for (const attribute in result) {
console.log(`Discovering ${attribute} belongs to object!`);
if (result.hasOwnProperty(attribute)) {
console.log(`${attribute} belongs to object!`);
}
}
对于其他一些对象属性,这种行为是可观察到的,但我可以使用result.attributeName
.
那么,什么可以解释这种行为呢?
解决方案
hasOwnProperty
返回false
继承的属性。我的猜测是该nutriments
属性实际上是由该对象继承的。我们使用它来实际避免一些继承的属性。
另一种可能性是,该对象要么是代理,要么其某些属性受 保护.defineProperty
,使它们要么不可迭代,要么不可“获取”。
正确诊断/解决方案需要更多信息。
推荐阅读
- java - (Java 接口) (Interface_name)class_name.newInstance() 在java 中是什么意思?
- java - 无法在 Selenium 和 Java 中使用 className 定位元素
- python - 将 datetime.now() 对象的时间与时间字符串进行比较
- javascript - 正则表达式匹配字符串中重复的属性值
- javascript - 如何制作地球进步派
- ios - React Native 与 RNFirebase 构建问题
- haskell - Haskell - 如何获得类型签名“a -> a -> a”?
- java - Java读取带有多个对象的JSON
- json - Jira Api:为什么在创建新问题时将描述与摘要合并?
- javascript - 如何让 Azure 上的 Node.js 以 ES6 模块语法启动,虽然它在家里工作,但现在失败了?