简体   繁体   中英

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:

{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

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). 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 => { /**/ }); as @str metions in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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