0

When i create associate array in javascript, i got a problem like that. I want to get the value by using field name as key, but i just only got undefined. What should i do to get value by key or which way is good approach for it.

Here is my code

function getFields(pVal){
    var tmpObj = {};
    str = pVal.split(",");
    for(i=0;i<str.length;i++){
        tmpVal = str[i].split(":");
        tmpObj[tmpVal[0]] = tmpVal[1];  
    }
    return tmpObj;
}

function JustTest(){
   var fields = {}; 
   fields = getFields("'Code':'PRJ001','Name':'Project 01'");
   alert(fields['Code']);
}
1
  • Where is this string from? It looks like it should be JSON. Commented Aug 9, 2012 at 11:23

2 Answers 2

4

Because the key is 'Code', not Code, note the single quote ', you need do alert(fields["'Code'"]);

PS: Please add ; at the end of statement, it is bad practice to omit them.

Sign up to request clarification or add additional context in comments.

3 Comments

prefixed semicolons are semicolons, so they are not optional.
when i create static object by using single code. i can retrieve value. in dynamically, i can not get the value. may i know about the difference.
0

I have re-factor the code, just try this:

function getFields(pVal) {
    var tmpObj = {};
    var str = pVal.split(",");
    for (var i = 0; i < str.length; i++) {
        var tmpVal = str[i].split(":");
        tmpObj[tmpVal[0]] = tmpVal[1];
    }
    return tmpObj;
}

function JustTest() {
    var fields = { };
    fields = getFields("'Code':'PRJ001','Name':'Project 01'");
    alert(fields["'Code'"]);
}

if you have question please comment below about code, thanks

1 Comment

i remove the single quote from parameters. because i can use 2 ways [fields['Code'] and fields.Code]

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.