irahn irahn - 6 months ago 17
JSON Question

How to create a Hashtable in javascript from a JSON by setting a value as the key?

I apologize if this is too vague, But I want to search each JSON object by a unique value and then spit out another value. I have been told it would be a good idea to create a Hash Table for this issue, but I do not know how to go about this. For example:

{
"form_key" : "basicPatientName",
"data" : "Miranda Jones",
"cid" : 2,
"pid" : 1,
"no" : "0"
}


I want to search
basicPatientName
and be able to pull
Miranda Jones
, or search basicPatientgender and pull 1.

I used a library called DefiantJS which lets me easily loop through my JSON and lets me do exactly what I am asking, but I have been told that there are too many iterations involved if I want to do this 1000+ times in the same program.

Answer

You could use this:

data = [{
    "form_key" : "basicPatientName",
    "data" : "Miranda Jones",
    "cid" : 2,
    "pid" : 1,
    "no" : "0"
},
{
    "form_key" : "basicPatientGender",
    "data" : "1",
    "cid" : 4,
    "pid" : 1,
    "no" : "0"
}
];

var result = {};
data.forEach(function (rec) {
    result[rec.form_key] = rec.data;
});

// output result
console.log(result);

// Example look-up use:
var data = result.basicPatientName; //  = Miranda Jones