【发布时间】:2020-01-04 14:04:42
【问题描述】:
我想使用 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') 返回 false...
for (const attribute in result) {
console.log(`Discovering ${attribute} belongs to object!`);
if (result.hasOwnProperty(attribute)) {
console.log(`${attribute} belongs to object!`);
}
}
这种行为对于其他一些对象属性是可观察到的,但我可以使用result.attributeName 获取属性值。
那么,什么可以解释这种行为呢?
【问题讨论】:
标签: json typescript for-loop