Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Javascript Convert Array to Object

Javascript Convert Array to Object

Problem

I have been using node and redis for some time. The problem I am experiencing is, when I use hgetall in redis, it returns an object.

 { uid: '6203453597',
    first_name: 'Name',
    last_name: 'Surname',
    gender: 'male',
    email: '[email protected]',
    status: '1',
    chips: '4002043' } 

However, when I use hmget and specify the fields I want to get, it returns an Array.

[ '6203453597', 'Name', 'Surname', '4002043' ]

So, I would like to convert array to an associative array, just like the first one. What is the best way to convert it from code and performance wise.

I am also using the multi command in redis. So it returns an array of objects in the first example, in the second example it return an array of arrays. So, it is important it to be efficient and automatic, not manual.

YUI's dataschema function is what I am looking for. However it needs to be done on node.js and the only 3rd party utility tool I am using is underscore. Is there any easy way of doing this, or do I need to convert hem in a loop, manually.

Thanks,

Problem courtesy of: Merinn

Solution

I have built something similar to what you want, but for the sort command. This should work for hmget:

function getFieldsAsObject(key, fields, next) {
    function mapResults(err, values) {
        if(err)
            return next(err);

        var result = {};
        for(var i = 0, len = fields.length; i 

EDIT: A version better suited for your example with multi hmget calls.

// Call with an array of fields and a function(err, results) {}
function mapResults (fields, next) {
    // Return a closure for a multi.exec call
    return function (err, replies) {
        if(err)
            return next(err);

        // Call next with no error and the replies mapped to objects
        next(null, replies.map(mapFields));
    };

    function mapFields (reply) {
        var obj = {};
        for(var i = 0, len = fields.length; i 

Sample usage:

var client = require("redis").createClient()
  , multi = client.multi();

multi.hmget("a.1", "foo", "bar");
multi.hmget("a.2", "foo", "bar");
multi.exec(mapResults(["foo", "bar"], function(err, results) {
    // results will be [{foo: 17, bar: 4711}, {foo: 42, bar: 3.1415926535897932384626433}]
    console.log(results);
}));
Solution courtesy of: Linus Gustav Larsson Thiel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Javascript Convert Array to Object

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×