简体   繁体   中英

array containing key-value pair javascript

So I have this "story" array:

 story[0]=[{"_ref":"/hierarchicalrequirement/15475417305","FormattedID":"US79832","Owner":"A","EstCP":0}]
 story[1]=[{"_ref":"/hierarchicalrequirement/15790056238","FormattedID":"US81776","Owner":"B","EstCP":0}]
 story[2]=[{"_ref":"/hierarchicalrequirement/15790059145","FormattedID":"US81777","Owner":"C","EstCP":7.5}]

How do I get the "FormattedID" key of story[2]? I tried:

1. story[2].get("FormattedID")
2. story[2].FormattedID
3. story[2]["FormattedID"]
4. story[2][FormattedID]
5. story[2].getCollection("FormattedID")
6. story[2].get(FormattedID)

None of these works. Any help would be appreciated. Thanks.

story[2] is an array with just one entry. You access that entry via [0] . That object has the property, so:

story[2][0].FormattedID

...gives you the value.

This may be clearer with some linebreaks. Here's what you're assigning to story[2] :

story[2]= [ // <== Starts array
    {       // <== Starts object
        "_ref": "/hierarchicalrequirement/15790059145",
        "FormattedID": "US81777",
        "Owner": "C",
        "EstCP": 7.5
    }       // <== Ends object
];          // <== Ends array

So story[2][0] gives us the object:

{
    "_ref": "/hierarchicalrequirement/15790059145",
    "FormattedID": "US81777",
    "Owner": "C",
    "EstCP": 7.5
}

...which has the FormattedID property. You can access that using dot notation and a literal property name ( .FormattedID ), or using bracketed notation and a string property name ( ["FormattedID"] ).

Remove the brackets when you are creating your story objects. Then you can get to it as you expect.

Example:

 story[0]={"_ref":"/hierarchicalrequirement/15475417305","FormattedID":"US79832","Owner":"A","EstCP":0}

story[0].FormattedID

With the brackets you are actually creating an array with one item at each spot in your main array.

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