1

I have an object like below I want to search/find element by based on "96f54547-767c-434b-bcb4-a239a36b1c56" and get an array ["x", "y"]. How to achieve this?

<script type="text/javascript">
var cList = {
    "96f54547-767c-434b-bcb4-a239a36b1c56": ["x","y"],
    "fd3f9224-9fa5-49f5-9eea-ffd0ff40fdb0": [null,"y"],
    "843ed981-979f-4639-be6d-93665e52246f": [null,"y"],
    "2208ca60-c0d1-4ee9-aaae-291bef9622fa": [null,"y"]
};     
</script>

2 Answers 2

6

You can use bracket operators to find the Array:

var values = cList["96f54547-767c-434b-bcb4-a239a36b1c56"];

Either hard-coded as above or with the key stored in another variable:

var guid = "96f54547-767c-434b-bcb4-a239a36b1c56";
var values = cList[guid];

Also, if you want to test whether the Object even has the key, you can use the in keyword:

if (!(guid in cList)) {
    throw new Error('Data does not include the expected GUID: ' + guid);
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm surprised people aren't jumping down your throat about using in instead of hasOwnProperty()
@Ian It's a good suggestion, but I don't think one is absolute over the other. There are use cases where acknowledging the prototype chain is the desired effect. Plus, in this case, shouldn't have to worry too much about the difference with a plain Object. There's far more opposition to extending Object.prototype. :)
My point was just that I get heckled when I don't, and I think it's silly. Too many people think the only "safe" way to check for an object literal's property is with hasOwnProperty...because of Crockford, Resig, blah blah blah. It's just good to see someone else be okay not using it :)
It's not a bad idea to mention both versions and explain the differences though.
1

you can try like this

 var value= cList["96f54547-767c-434b-bcb4-a239a36b1c56"]

4 Comments

Did you try that first option before recommending it? (Stack Overflow's colour-based syntax highlighting should give you a hint as to why it won't work...)
Didn't tried with this code, but I have implemented it in my code some time ago
That first option is saying cList.96f54547 minus 767c minus 434b minus bcb4 minus a239a36b1c56. Note that the second option is the same as in the answer that was posted seventeen minutes before yours...
Thanks for giving me the direction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.