Scott Sauyet
3/4/2015 8:15:00 PM
Masoom Tulsiani wrote:
> I have the following hash structure with nested key/value pairs.
As Denis mentioned, your structure took some rework before it could be comfortably loaded in JS. This was my version:
var hash = [
{
OBJ_TYPE: 'RESULT',
NAME: 'Result.ResultName',
FIELDS: [
{UNAME: 'STRING', DESC: 'STRING'}
]
},
{
OBJ_TYPE: 'FEED',
NAME: 'Feed.FeedName',
FIELDS: [
{UNAME: 'STRING', DESC: 'STRING'}
]
},
{
OBJ_TYPE: 'X',
NAME: 'X.XName',
FIELDS: [
{UNAME: 'STRING', DESC: 'STRING'}
]
}
];
> How can I access a particular key and value pair. For Instance,I would
> like to access FIELDS -> UNAME(key) and FIELDS -> STRING (value) of
> the message with OBJ_TYPE: FEED
This function applies a callback function to each matching field:
var processFields = function(hash, type, name, fn) {
hash.filter(function(obj) {
return obj.OBJ_TYPE === type && obj.NAME === name;
}).forEach(function(obj) {
obj.FIELDS.forEach(function(field) {fn(field);});
});
};
processFields(hash, 'FEED', 'Feed.FeedName', function(field) {
console.log(field);
}); // logs {UNAME: "STRING", DESC: "STRING"}
It could easily be modified to collect and return the fields instead of
applying a callback, though.
HTH,
-- Scott