首页 > 解决方案 > 用于循环和 hasOwnProperty 的 ecma 脚本有一个奇怪的行为

问题描述

我想使用 DTO 转换从 NoSQL 数据库获取的对象,因此,我在for..in循环中检查对象以仅获取我想要保留的内容:

for (const attribute in result) {
    if (result.hasOwnProperty(attribute)) {
        console.log(`${attribute} belongs to object!`);
    }
}

我想知道为什么 :

这是原始对象的一部分:

...
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.

那么,什么可以解释这种行为呢?

标签: jsontypescriptfor-loop

解决方案


hasOwnProperty返回false继承的属性。我的猜测是该nutriments属性实际上是由该对象继承的。我们使用它来实际避免一些继承的属性。

另一种可能性是,该对象要么是代理,要么其某些属性受 保护.defineProperty,使它们要么不可迭代,要么不可“获取”。

正确诊断/解决方案需要更多信息。


推荐阅读