简体   繁体   English

在javascript中访问另一个对象内的对象

[英]Accessing object inside another object in javascript

I have a following object:我有以下对象:

DOMAIN_ROLE:{
    type: "Domain"
    DomainName: "XYZ"
    DomainCode: 21
    Title: "People Role"
    CodedValues:{
        1: {Code: 1, Label: "Land"},
        2: {Code: 2, Label: "Forest"},
        3: {Code: 3, Label: "Public"},
        4: {Code: 4, Label: "Single"},
        5: {Code: 5, Label: "Private"}
       }
}

What I am trying to do is map through this data where object named "CodedValues" has index of 1 , 2 and 5 as shown below:我想要做的是映射这个数据,其中名为“CodedValues”的对象的索引为 1 、 2 和 5 ,如下所示:

{Object.keys(DOMAIN_ROLE.CodedValues[1,2,5]).map(key =>{
          return (
          <div>...</div>
            );
}

The problem is while mapping through, the "key" get's the value as "Code" instead of number ie 1,2,3... it seems key becomes key = CodedValues.Code, where I want to work as key = 1, key = 2, key = 5问题是在映射时,“键”得到的值是“代码”而不是数字,即 1,2,3...似乎键变成了键 = CodedValues.Code,我想在其中作为键 = 1 工作,键 = 2,键 = 5

Tried to explain in best possible way.试图以最好的方式解释。 Any suggestion would be helpful.任何建议都会有所帮助。

 let DOMAIN_ROLE = { type: "Domain", DomainName: "XYZ", DomainCode: 21, Title: "People Role", CodedValues:{ 1: {Code: 1, Label: "Land"}, 2: {Code: 2, Label: "Forest"}, 3: {Code: 3, Label: "Public"}, 4: {Code: 4, Label: "Single"}, 5: {Code: 5, Label: "Private"} } } // you can use object destructuring to get the data by key. const {1:first,2:second, 5:fifth} = DOMAIN_ROLE.CodedValues; console.log(first,second, fifth) //[first, second, fifth].map(()=>{})

DOMAIN_ROLE.CodedValues[1,2,5] does not actually what you expect (get items with keys 1,2 and 5). DOMAIN_ROLE.CodedValues[1,2,5]实际上并不是您所期望的(使用键 1,2 和 5 获取项目)。 You have to get all the keys and filter them and use it:您必须获取所有密钥并对其进行过滤并使用它:

Object.keys(DOMAIN_ROLE.CodedValues).filter(k => /* filter logic */).map(key => {
    // Use key here: DOMAIN_ROLE[key]
});

This is helpful if you want to filter your keys based on some logic.如果您想根据某些逻辑过滤键,这会很有帮助。 If you are going to hard-code the keys why not just use ['1', '2', '5'].map(key => { /**/ });如果您要对键进行硬编码,为什么不直接使用['1', '2', '5'].map(key => { /**/ }); as @str metions in the comments.作为评论中的@str meions。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM