React如何获取动态生成的对象名称

问题描述 投票:-2回答:3

我在访问对象中的数据时遇到问题,我的对象是

profile: Object {
  "-L6LmpGWAClPdVK-cqvh": Object {
    "first_name": "Mithun",
    "isActive": true,
    "isPrimary": true,
    "last_name": "N",
    "phoneNumber": "123454649",
    "title": "Manager",
    "uid": "Vz0pWQV3UxeCbGCbaf7ld4kaNRE3",
  },
  "active": true,
  "businessCategory": "Retail",
  "companyName": "Test"
}

现在我的问题是:

如何访问-L6LmpGWAClPdVK-cqvh值,这个-L6LmpGWAClPdVK-cqvh是动态生成的随机密钥。

我可以获得this.props.profile.email的价值

同样如何获得this.props.profile.-L6LmpGWAClPdVK-cqvh.first_name(目前它说未定义)

请帮忙!!!

javascript json reactjs object react-native
3个回答
2
投票

在JavaScript中,有两种方法可以访问对象中的属性。点符号object.property和方括号符号对象['property']。如果您知道该属性的名称,这两个都有效。如果您有一个存储属性名称的变量,或者您的属性包含对属性无效的字符,那么您只能使用方形表示法。

var key = '-L6LmpGWAClPdVK-cqvh';
var value = object[key];

所以在你的情况下,你将不得不使用this.props.profile['-L6LmpGWAClPdVK-cqvh'].first_name。随机名称中的-不能用作原始密钥,必须是字符串。

JS解析器会认为你正在做this.props.profile. - L6LmpGWAClPdVK - cqvh.first_name。为清楚起见,添加了空格。


0
投票

在这种情况下,键包含字符“ - ”,它阻止您通过对象访问。(点)所以你必须使用object ['string']


0
投票
We can able to iterate the object. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). On iterating the object will return the keys that the object has. You can access the object values by using dot (.) notation and also by using bracket ([]) notation

for (var data in profile) {
    if (data.hasOwnProperty(propName)) { //eg: propName which is first_name
        var propValue = data[propName];
        // do something with each element here
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.